From 7edf3fee67da586f7240df56635d3531c4302048 Mon Sep 17 00:00:00 2001 From: Hernan Grecco Date: Fri, 8 Jan 2016 01:06:58 -0300 Subject: [PATCH] Removed try/except block in Quantity.dimensionality As the Quantity class has an expensive __getattr__ this check was having a measurable performance hit. Close #251 --- docs/systems.rst | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ pint/quantity.py | 6 +++--- 2 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 docs/systems.rst diff --git a/docs/systems.rst b/docs/systems.rst new file mode 100644 index 0000000..fbf1288 --- /dev/null +++ b/docs/systems.rst @@ -0,0 +1,56 @@ +.. systems_: + +Different Unit Systems (and default units) +========================================== + +Pint Unit Registry has the concept of system, which is a group of units + + >>> import pint + >>> ureg = pint.UnitRegistry(system='mks') + >>> ureg.system + 'mks' + +This has an effect in the base units. For example: + + >>> q = 3600. * ureg.meter / ureg.hour + >>> q.to_base_units() + + +We can take a look for the available systems + + >>> ureg.systems + frozenset({'US', 'mks', 'imperial', 'cgs'}) + +But if you change to cgs: + + >>> ureg.system = 'cgs' + >>> q.to_base_units() + + +or more drastically to: + + >>> ureg.system = 'imperial' + >>> '{:.3f}'.format(q.to_base_units()) + '1.094 yard / second' + +..warning: In versions previous to 0.7 `to_base_units` returns quantities in the + units of the definition files (which are called root units). For the definition file + bundled with pint this is meter/gram/second. To get back this behaviour use `to_root_units`, + set `ureg.system = None` + + +You can also use system to narrow down the list of compatible units: + + >>> ureg.system = 'mks' + >>> ureg.get_compatible_units('meter') + frozenset({, , , , , , , , , , , }) + + + >>> ureg.system = 'imperial' + >>> ureg.get_compatible_units('meter') + frozenset({, , , , , , , , , , , }) + + >>> ureg.imperial.pint + bla + + >>> ureg.us.pint diff --git a/pint/quantity.py b/pint/quantity.py index 7243862..22dc875 100644 --- a/pint/quantity.py +++ b/pint/quantity.py @@ -198,13 +198,13 @@ class _Quantity(SharedRegistryObject): return not bool(tmp.dimensionality) + _dimensionality = None + @property def dimensionality(self): """Quantity's dimensionality (e.g. {length: 1, time: -1}) """ - try: - return self._dimensionality - except AttributeError: + if self._dimensionality is None: self._dimensionality = self._REGISTRY._get_dimensionality(self._units) return self._dimensionality