importsysfromtypingimportTYPE_CHECKING,Literal,Type,Unionfrom.attrseriesimportAttrSeriesfrom.baseimportBaseQuantityfrom.sparsedataarrayimportSparseDataArrayifTYPE_CHECKING:# TODO Remove this block once Python 3.10 is the lowest supported versionfromtypingimportTypeAlias
[docs]defassert_quantity(*args):"""Assert that each of `args` is a Quantity object. Raises ------ TypeError with a indicative message. """fori,arginenumerate(args):ifnotisinstance(arg,BaseQuantity):raiseTypeError(f"arg #{i+1} ({repr(arg)[:20]}) is not Quantity; likely an incorrect key")
[docs]defget_class()->Type[Union[AttrSeries,SparseDataArray]]:"""Get the current :class:`.Quantity` implementation in use. Returns one of the classes :class:`.AttrSeries` or :class:`.SparseDataArray`. """globalQuantityreturnQuantity
[docs]defset_class(name:Literal["AttrSeries","SparseDataArray"]="AttrSeries",)->Type[Union[AttrSeries,SparseDataArray]]:"""Set the :class:`.Quantity` implementation to be used. This also updates :py:`genno.Quantity` and :py:`genno.quantity.Quantity` to refer to the selected class. It does **not** update previously-imported references to one class or the other; code that uses :func:`.set_class` should refer to one of those two locations: .. code-block:: import genno from genno import Quantity # AttrSeries, by default Quantity() # AttrSeries genno.Quantity() # AttrSeries genno.set_class("SparseDataArray") Quantity() # AttrSeries genno.Quantity() # SparseDataArray Another approach is to update the local reference with the return value of the function: .. code-block:: python from genno import Quantity, set_class Quantity() # AttrSeries Quantity = set_class("SparseDataArray") Quantity() # SparseDataArray In code that does not use :func:`.set_class`, :py:`from genno import Quantity` is safe. See also -------- .AnyQuantity """globalCLASStry:cls={"AttrSeries":AttrSeries,"SparseDataArray":SparseDataArray}[name]exceptKeyError:raiseValueError(f"no Quantity implementation {name}")# Update globals in the current module and at the top levelformodulein"genno.core.quantity","genno":setattr(sys.modules[module],"Quantity",cls)# Update globalCLASS=cls.__name__returncls
#: Class used to implement :class:`.Quantity`.Quantity:"TypeAlias"=AttrSeries#: Name of :class:`.Quantity`.CLASS="AttrSeries"#: Either :class:`.AttrSeries` or :class:`.SparseDataArray`. Code in :mod:`genno` or#: user code that receives or returns any Quantity implementation should be typed with#: this type.AnyQuantity=Union[AttrSeries,SparseDataArray]