earthkit.utils.units.Units

class earthkit.utils.units.Units[source]

Bases: object

Abstract 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:

PintUnits

Wraps a pint.Unit object. Created when the input string can be successfully parsed by Pint. to_pint() returns the underlying pint.Unit, enabling further Pint-based arithmetic and dimensional analysis.

StrUnits

Stores the unit as a plain string. Created as a fallback when Pint cannot parse the input. to_pint() returns None.

Use to_pint() to obtain the underlying pint.Unit when interoperability with the Pint library is needed. Callers should guard against None to 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 underlying pint.Unit and 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 None from to_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 Units instance from various input types.

to_pint()

Return the underlying Pint unit, or None if not available.

static from_any(units)[source]

Construct a Units instance from various input types.

Parameters:

units (str, None, pint.Unit, or Units) – The unit to convert. Strings and None are parsed and, where possible, resolved to a Pint-backed unit. pint.Unit objects are wrapped directly. Existing Units instances are returned unchanged.

Returns:

A PintUnits or StrUnits instance.

Return type:

Units

Raises:

ValueError – If units is of an unsupported type.

abstractmethod to_pint() Unit | None[source]

Return the underlying Pint unit, or None if not available.

Returns:

The Pint unit, or None if this unit cannot be represented as a Pint unit.

Return type:

pint.Unit or None