forked from M-Labs/artiq
1
0
Fork 0

language/units: add strip_unit function

This commit is contained in:
Sebastien Bourdeauducq 2015-02-26 23:31:07 -07:00
parent 14e481d154
commit ee9d616733
1 changed files with 23 additions and 0 deletions

View File

@ -239,3 +239,26 @@ def check_unit(value, unit):
else:
if not isinstance(value, Quantity) or value.unit != unit:
raise DimensionError
def strip_unit(value, unit):
"""Check that the value has the specified unit and returns its amount.
Raises ``DimensionError`` if the units does not match.
If the passed value is not a ``Quantity``, it is assumed to be in the
specified unit and is returned unchanged.
If ``unit`` is ``None``, passing a ``Quantity`` as value raises
``DimensionError``.
"""
if unit is None:
if isinstance(value, Quantity):
raise DimensionError
else:
return value
else:
if isinstance(value, Quantity):
if value.unit != unit:
raise DimensionError
else:
return value.amount