Improved documentation

This commit is contained in:
Hernan Grecco
2016-02-09 22:58:38 -03:00
parent 221daf9486
commit 88d196bf8d
8 changed files with 59 additions and 30 deletions

View File

@@ -17,8 +17,7 @@ raise an error if your do this directly:
>>> q.to('Hz') >>> q.to('Hz')
Traceback (most recent call last): Traceback (most recent call last):
... ...
pint.unit.DimensionalityError: Cannot convert pint.errors.DimensionalityError: Cannot convert from 'nanometer' ([length]) to 'hertz' (1 / [time])
from 'nanometer' ([length]) to 'hertz' (1 / [time])
You probably want to use the relation `frequency = speed_of_light / wavelength`: You probably want to use the relation `frequency = speed_of_light / wavelength`:

View File

@@ -57,7 +57,7 @@ you don't want to append the translated definitions so you just give the
filename to the constructor:: filename to the constructor::
>>> from pint import UnitRegistry >>> from pint import UnitRegistry
>>> ureg = UnitRegistry('/your/path/to/default_es.txt') >>> ureg = UnitRegistry('/your/path/to/default_es.txt') # doctest: +SKIP
In the definition file, prefixes are identified by a trailing dash:: In the definition file, prefixes are identified by a trailing dash::

View File

@@ -15,9 +15,12 @@ or using easy_install_::
That's all! You can check that Pint is correctly installed by starting up python, and importing pint: That's all! You can check that Pint is correctly installed by starting up python, and importing pint:
.. testcode::
>>> import pint >>> import pint
>>> pint.__version__ >>> pint.__version__
0.5
.. testoutput::
|version|
.. note:: If you have an old system installation of Python and you don't want to .. note:: If you have an old system installation of Python and you don't want to
mess with it, you can try `Anaconda CE`_. It is a free Python distribution by mess with it, you can try `Anaconda CE`_. It is a free Python distribution by
@@ -25,7 +28,7 @@ That's all! You can check that Pint is correctly installed by starting up python
You can check the installation with the following command: You can check the installation with the following command:
>>> pint.test() >>> pint.test() # doctest: +SKIP
On Arch Linux, you can alternatively install Pint from the Arch User Repository On Arch Linux, you can alternatively install Pint from the Arch User Repository

View File

@@ -18,6 +18,7 @@ For example, to convert from celsius to fahrenheit:
from pint import UnitRegistry from pint import UnitRegistry
ureg = UnitRegistry() ureg = UnitRegistry()
ureg.default_format = '.3f'
Q_ = ureg.Quantity Q_ = ureg.Quantity
.. doctest:: .. doctest::
@@ -196,4 +197,4 @@ this is the definition of the celsius and fahrenheit::
You do not need to define *delta* units, as they are defined automatically. You do not need to define *delta* units, as they are defined automatically.
.. [#f1] If the exponent is +1, the quantity will not be converted to base .. [#f1] If the exponent is +1, the quantity will not be converted to base
unit but remains unchanged. unit but remains unchanged.

View File

@@ -57,30 +57,40 @@ best way is to create a tuple with the magnitude and the units:
.. doctest:: .. doctest::
>>> to_serialize = duration.magnitude, duration.units >>> to_serialize = duration.to_tuple()
>>> print(to_serialize)
(24.2, (('year', 1.0),))
Or the most robust way which avoids Pint classes:: And then you can just pickle that:
>>> to_serialize = duration.magnitude, tuple(duration.units.items())
and then use your usual serialization function. For example, using the pickle protocol.
>>> import pickle >>> import pickle
>>> serialized = pickle.dumps(to_serialize, -1) >>> serialized = pickle.dumps(to_serialize, -1)
To unpickle, just To unpickle, just
>>> magnitude, units = pickle.loads(serialized) >>> loaded = pickle.loads(serialized)
>>> ureg.Quantity(magnitude, units) >>> ureg.Quantity.from_tuple(loaded)
<Quantity(24.2, 'year')> <Quantity(24.2, 'year')>
(To pickle to and from a file just use the dump and load method as described in _Pickle)
You can use the same mechanism with any serialization protocol, not only with binary ones. You can use the same mechanism with any serialization protocol, not only with binary ones.
(In fact, version 0 of the Pickle protocol is ASCII). Other common serialization protocols/packages (In fact, version 0 of the Pickle protocol is ASCII). Other common serialization protocols/packages
are json_, yaml_, shelve_, hdf5_ (or via PyTables_) and dill_. are json_, yaml_, shelve_, hdf5_ (or via PyTables_) and dill_.
Notice that not all of these packages will serialize properly the magnitude (which can be any Notice that not all of these packages will serialize properly the magnitude (which can be any
numerical type such as `numpy.ndarray`) numerical type such as `numpy.ndarray`).
Using the serialize_ package you can load and read from multiple formats:
>>> from serialize import dump, load, register_class
>>> register_class(ureg.Quantity, ureg.Quantity.to_tuple, ureg.Quantity.from_tuple)
>>> dump(duration, 'output.yaml')
>>> r = load('output.yaml')
(Check out the serialize_ docs for more information)
.. _serialize: https://github.com/hgrecco/serialize
.. _Pickle: http://docs.python.org/3/library/pickle.html .. _Pickle: http://docs.python.org/3/library/pickle.html
.. _json: http://docs.python.org/3/library/json.html .. _json: http://docs.python.org/3/library/json.html
.. _yaml: http://pyyaml.org/ .. _yaml: http://pyyaml.org/

View File

@@ -7,7 +7,7 @@ Pint Unit Registry has the concept of system, which is a group of units
>>> import pint >>> import pint
>>> ureg = pint.UnitRegistry(system='mks') >>> ureg = pint.UnitRegistry(system='mks')
>>> ureg.system >>> ureg.default_system
'mks' 'mks'
This has an effect in the base units. For example: This has an effect in the base units. For example:
@@ -23,13 +23,13 @@ We can take a look for the available systems
But if you change to cgs: But if you change to cgs:
>>> ureg.system = 'cgs' >>> ureg.default_system = 'cgs'
>>> q.to_base_units() >>> q.to_base_units()
<Quantity(100.0, 'centimeter / second')> <Quantity(100.0, 'centimeter / second')>
or more drastically to: or more drastically to:
>>> ureg.system = 'imperial' >>> ureg.default_system = 'imperial'
>>> '{:.3f}'.format(q.to_base_units()) >>> '{:.3f}'.format(q.to_base_units())
'1.094 yard / second' '1.094 yard / second'
@@ -41,16 +41,30 @@ or more drastically to:
You can also use system to narrow down the list of compatible units: You can also use system to narrow down the list of compatible units:
>>> ureg.system = 'mks' >>> ureg.default_system = 'mks'
>>> ureg.get_compatible_units('meter') >>> ureg.get_compatible_units('meter')
frozenset({<Unit('light_year')>, <Unit('angstrom')>, <Unit('US_survey_mile')>, <Unit('yard')>, <Unit('US_survey_foot')>, <Unit('US_survey_yard')>, <Unit('inch')>, <Unit('rod')>, <Unit('mile')>, <Unit('barleycorn')>, <Unit('foot')>, <Unit('mil')>}) frozenset({<Unit('light_year')>, <Unit('angstrom')>})
or for imperial units:
>>> ureg.system = 'imperial' >>> ureg.default_system = 'imperial'
>>> ureg.get_compatible_units('meter') >>> ureg.get_compatible_units('meter')
frozenset({<Unit('US_survey_mile')>, <Unit('angstrom')>, <Unit('inch')>, <Unit('light_year')>, <Unit('barleycorn')>, <Unit('mile')>, <Unit('US_survey_foot')>, <Unit('rod')>, <Unit('US_survey_yard')>, <Unit('yard')>, <Unit('mil')>, <Unit('foot')>}) frozenset({<Unit('thou')>, <Unit('league')>, <Unit('nautical_mile')>, <Unit('inch')>, <Unit('mile')>, <Unit('yard')>, <Unit('foot')>})
>>> ureg.imperial.pint
bla
>>> ureg.us.pint You can check which unit systems are available:
>>> dir(ureg.sys)
['US', 'cgs', 'imperial', 'mks']
Or which units are available within a particular system:
>>> dir(ureg.sys.imperial)
['acre', 'acre_foot', 'board_foot', 'cable', 'chain', 'fathom', 'foot', 'furlong', 'imperial_bushel', 'imperial_cup', 'imperial_fluid_ounce', 'imperial_gallon', 'imperial_gill', 'imperial_pint', 'imperial_quart', 'inch', 'league', 'mile', 'nautical_mile', 'perch', 'pica', 'point', 'rood', 'square_foot', 'square_yard', 'thou', 'yard']
Notice that this give you the opportunity to choose within units with colliding names:
>>> (1 * ureg.sys.imperial.pint).to('liter')
<Quantity(0.5682612500000002, 'liter')>
>>> (1 * ureg.sys.US.pint).to('liter')
<Quantity(0.47317647300000004, 'liter')>

View File

@@ -76,6 +76,7 @@ use the `ito` method:
.. doctest:: .. doctest::
>>> speed.ito(ureg.inch / ureg.minute ) >>> speed.ito(ureg.inch / ureg.minute )
>>> speed
<Quantity(7086.614173228345, 'inch / minute')> <Quantity(7086.614173228345, 'inch / minute')>
>>> print(speed) >>> print(speed)
7086.614173228345 inch / minute 7086.614173228345 inch / minute
@@ -134,7 +135,7 @@ If you try to use a unit which is not in the registry:
>>> speed = 23 * ureg.snail_speed >>> speed = 23 * ureg.snail_speed
Traceback (most recent call last): Traceback (most recent call last):
... ...
pint.pint.UndefinedUnitError: 'snail_speed' is not defined in the unit registry pint.errors.UndefinedUnitError: 'snail_speed' is not defined in the unit registry
You can add your own units to the registry or build your own list. More info on You can add your own units to the registry or build your own list. More info on
that :ref:`defining` that :ref:`defining`
@@ -223,7 +224,7 @@ LaTeX representations:
>>> accel = 1.3 * ureg['meter/second**2'] >>> accel = 1.3 * ureg['meter/second**2']
>>> # Pretty print >>> # Pretty print
>>> print('The pretty representation is {:P}'.format(accel)) >>> 'The pretty representation is {:P}'.format(accel)
'The pretty representation is 1.3 meter/second²' 'The pretty representation is 1.3 meter/second²'
>>> # Latex print >>> # Latex print
>>> 'The latex representation is {:L}'.format(accel) >>> 'The latex representation is {:L}'.format(accel)
@@ -242,8 +243,8 @@ If you want to use abbreviated unit names, prefix the specification with `~`:
>>> 'The str is {:~}'.format(accel) >>> 'The str is {:~}'.format(accel)
'The str is 1.3 m / s ** 2' 'The str is 1.3 m / s ** 2'
>>> print('The pretty representation is {:~P}'.format(accel)) >>> 'The pretty representation is {:~P}'.format(accel)
The pretty representation is 1.3 m²/s 'The pretty representation is 1.3 m/s²'
The same is true for latex (`L`) and HTML (`H`) specs. The same is true for latex (`L`) and HTML (`H`) specs.
@@ -300,6 +301,7 @@ also define the registry as the application registry::
>>> q2 = UnitRegistry().meter >>> q2 = UnitRegistry().meter
>>> # q1 and q2 belong to different registries! >>> # q1 and q2 belong to different registries!
>>> id(q1._REGISTRY) == id(q2._REGISTRY) # False >>> id(q1._REGISTRY) == id(q2._REGISTRY) # False
False
.. _eval: http://docs.python.org/3/library/functions.html#eval .. _eval: http://docs.python.org/3/library/functions.html#eval
.. _dangerous: http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html .. _dangerous: http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

View File

@@ -163,7 +163,7 @@ In the decorator format:
.. doctest:: .. doctest::
>>>@ureg.check('[length]') >>> @ureg.check('[length]')
... def pendulum_period(length): ... def pendulum_period(length):
... return 2*math.pi*math.sqrt(length/G) ... return 2*math.pi*math.sqrt(length/G)