earthkit.utils.units.Units¶
- class earthkit.utils.units.Units[source]¶
Bases:
objectAbstract base class representing a physical unit.
Provides an interface for unit representations that may or may not be backed by a Pint unit.
Two concrete implementations exist:
PintUnitsWraps a
pint.Unitobject. Created when the input string can be successfully parsed by Pint.to_pint()returns the underlyingpint.Unit, enabling further Pint-based arithmetic and dimensional analysis.StrUnitsStores the unit as a plain string. Created as a fallback when Pint cannot parse the input.
to_pint()returnsNone.
Use
to_pint()to obtain the underlyingpint.Unitwhen interoperability with the Pint library is needed. Callers should guard againstNoneto handle unrecognised unit strings gracefully.Examples
Create a unit from a string — equivalent notations resolve to the same unit:
>>> from earthkit.utils.units import Units >>> u = Units.from_any("m/s") >>> str(u) 'meter / second' >>> Units.from_any("m s-1") == u True >>> Units.from_any("m s^-1") == u True
Units can also be compared directly with strings:
>>> u == "m s-1" True
Use
to_pint()to retrieve the underlyingpint.Unitand perform Pint-based operations such as unit conversion:>>> pint_unit = u.to_pint() >>> pint_unit <Unit('meter / second')> >>> from earthkit.utils.units.units import ureg >>> quantity = 10 * ureg.meter / ureg.second >>> quantity.to(pint_unit) <Quantity(10, 'meter / second')>
The
(0 - 1)alias is recognised as a percentage:>>> str(Units.from_any("(0 - 1)")) 'percent' >>> Units.from_any("(0 - 1)") == "%" True
Unknown unit strings are stored as-is and return
Nonefromto_pint():>>> u_invalid = Units.from_any("invalid") >>> str(u_invalid) 'invalid' >>> u_invalid.to_pint() is None True
- __init__()¶
Methods
__init__()from_any(units)Construct a
Unitsinstance from various input types.to_pint()Return the underlying Pint unit, or
Noneif not available.- static from_any(units)[source]¶
Construct a
Unitsinstance from various input types.- Parameters:
units (str, None, pint.Unit, or Units) – The unit to convert. Strings and
Noneare parsed and, where possible, resolved to a Pint-backed unit.pint.Unitobjects are wrapped directly. ExistingUnitsinstances are returned unchanged.- Returns:
A
PintUnitsorStrUnitsinstance.- Return type:
- Raises:
ValueError – If units is of an unsupported type.