[docs]@attrs.defineclassUnitGenerator:""" A callable object which returns units objects. Stored units can be contextually overridden using the :meth:`~pinttrs.UnitGenerator.override` method. .. seealso:: :class:`~pinttrs.UnitContext` :Attributes / constructor arguments: **units** (:class:`pint.Unit` or :class:`Callable`) – Stored units or generator. """units:Union[pint.Unit,Callable]=attrs.field()
[docs]def__call__(self)->pint.Unit:""" :returns: If ``units`` is a :class:`pint.Unit`, it is returned; if ``units`` is a callable (typically, another :class:`~pinttrs.UnitGenerator`), the result of its evaluation will be returned. """ifcallable(self.units):returnself.units()returnself.units
[docs]@contextmanagerdefoverride(self,units:Union[pint.Unit,Callable,str])->None:""" Temporarily override the value of ``units``. The initial value of ``units`` is restored upon leaving context. :param units: Temporary replacement for ``units``. String values are interpreted based on the unit registry of currently stored units. """units_old=copy(self.units)ifisinstance(units,str):# Safeguard to convert stringsifcallable(self.units):self.units=self.units()._REGISTRY.Unit(units)else:self.units=self.units._REGISTRY.Unit(units)else:self.units=unitstry:yieldfinally:self.units=units_old