pintext.attrs#
The attrs integration. Requires the attrs extra:
python -m pip install "pintext[attrs]"
See also
- 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
NOTHINGandunitsis notNone, defaults tohas_compatible_units()(possibly wrapped inattrs.validators.optional()ifdefaultisNone). Otherwise retains original behaviour.repr – If set to
NOTHINGandunitsis notNone, defaults to a callable printing quantities nicely. Otherwise retains original behaviour.converter – If set to
NOTHINGandunitsis notNone, defaults toensure_units(default_units=units)(possibly wrapped inattrs.converters.optional()ifdefaultisNone). Otherwise retains original behaviour.on_setattr – If set to
NOTHINGandunitsis notNone, defaults toattrs.setters.pipe(attrs.setters.convert, attrs.setters.validate). Otherwise retains original behaviour.units (
Unit|UnitGenerator|None) – Default units attached to the defined attribute. Accepts aUnitGeneratorinstance. Has no effect if set toNone.
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 aUnitContext) 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
valuehas units compatible (in the sense ofunits_compatible()) withattribute.This validator checks that a Pint quantity has units compatible with the units declared for an attribute. It raises
UnitsErrorif 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: