From ee9d616733456b3f8c2135634208669bf2014ccd Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Thu, 26 Feb 2015 23:31:07 -0700 Subject: [PATCH] language/units: add strip_unit function --- artiq/language/units.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/artiq/language/units.py b/artiq/language/units.py index c15bf7e01..52a456e3a 100644 --- a/artiq/language/units.py +++ b/artiq/language/units.py @@ -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