pintext.attrs#

The attrs integration. Requires the attrs extra:

python -m pip install "pintext[attrs]"
pintext.attrs.field(*, default=NOTHING, validator=NOTHING, repr=NOTHING, hash=None, init=True, metadata=None, converter=NOTHING, factory=None, kw_only=False, eq=None, order=None, on_setattr=NOTHING, units=None)[source]#

Create a new attribute on a class, possibly with units. This function wraps attrs.field() and retains its behaviour unless otherwise specified.

Parameters:
  • validator – If set to NOTHING and units is not None, defaults to has_compatible_units() (possibly wrapped in attrs.validators.optional() if default is None). Otherwise retains original behaviour.

  • repr – If set to NOTHING and units is not None, defaults to a callable printing quantities nicely. Otherwise retains original behaviour.

  • converter – If set to NOTHING and units is not None, defaults to ensure_units(default_units=units) (possibly wrapped in attrs.converters.optional() if default is None). Otherwise retains original behaviour.

  • on_setattr – If set to NOTHING and units is not None, defaults to attrs.setters.pipe(attrs.setters.convert, attrs.setters.validate). Otherwise retains original behaviour.

  • units (Unit | UnitGenerator | None) – Default units attached to the defined attribute. Accepts a UnitGenerator instance. Has no effect if set to None.

Examples

>>> @attrs.define
... class Sphere:
...     radius: pint.Quantity = field(units=ureg.m)
>>> Sphere(radius=1.0)
Sphere(radius=1.0 m)
>>> Sphere(radius=1.0 * ureg.km)
Sphere(radius=1.0 km)

Passing a UnitGenerator (typically obtained from a UnitContext) defers unit evaluation:

>>> generator = UnitGenerator(ureg.m)
>>> @attrs.define
... class Sphere:
...     radius: pint.Quantity = field(units=generator)
>>> with generator.override(ureg.km):
...     Sphere(radius=1.0)
Sphere(radius=1.0 km)
pintext.attrs.has_compatible_units(instance, attribute, value)[source]#

Validate if value has units compatible (in the sense of units_compatible()) with attribute.

This validator checks that a Pint quantity has units compatible with the units declared for an attribute. It raises UnitsError if the units are incompatible or if a unitless value is provided.

Only works with unit-enabled fields created with pintext.attrs.field().

This is a thin adapter around pintext.check_units(), which holds the actual check and is shared with the pydantic integration.

Parameters:
  • instance – The class instance being validated.

  • attribute – The attrs attribute being validated (must have units metadata).

  • value – The value to validate (should be a Pint quantity).

Raises:

UnitsError – If units are incompatible or if a unitless value is provided.

Return type:

None

class pintext.attrs.MetadataKey(*values)[source]#

Attribute metadata keys.

These Enum values should be used as metadata attribute keys. They are immutable and guarantee that no collision can occur with another piece of code.