API Reference#

Main interface#

pinttr.ib(default=_Nothing.NOTHING, validator=_Nothing.NOTHING, repr=_Nothing.NOTHING, cmp=None, hash=None, init=True, metadata=None, type=None, converter=_Nothing.NOTHING, factory=None, kw_only=False, eq=None, order=None, on_setattr=_Nothing.NOTHING, units=None)#

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

  • validator – If set to NOTHING and units is not None, defaults to has_compatible_units() (possibly wrapped in attr.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 to_units(units) (possibly wrapped in attr.converters.optional() if default is None). Otherwise retains original behaviour.

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

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

Changed in version 21.3.0: Added prettier default repr.

Dynamic unit management#

class pinttr.UnitGenerator(units)[source]#

A callable object which returns units objects. Stored units can be contextually overridden using the override() method.

See also


Attributes / constructor arguments:

units (pint.Unit or Callable) – Stored units or generator.

Return type:



If units is a pint.Unit, it is returned; if units is a callable (typically, another UnitGenerator), the result of its evaluation will be returned.


Temporarily override the value of units. The initial value of units is restored upon leaving context.


units (Union[Unit, Callable, str]) – Temporary replacement for units. String values are interpreted based on the unit registry of currently stored units.

Return type:


class pinttr.UnitContext(registry=_Nothing.NOTHING, interpret_str=False, ureg=None, key_converter=<function identity>)[source]#

An overridable registry of UnitGenerator objects.

This class maintains a registry of UnitGenerator instances. Stored UnitGenerator objects can be conveniently overridden using the override() context manager.

Attributes / constructor arguments:
  • registry (Dict[Hashable, UnitGenerator]) – Unit generator registry. Keys can be any hashable type, but str or Enum are recommended. Defaults to an empty dictionary.


    The initialisation sequence will make repeated calls to register() and will consequently apply the same key and value conversion rules.

  • interpret_str (bool) – If True, attempt string-to-units interpretation when specifying unit generators as str.

  • ureg (Optional[UnitRegistry]) – Unit registry used for string-to-units interpretation. If None, the default registry is used (see get_unit_registry()).

  • key_converter (Callable) – Converter used for keys. Defaults to identity().

Changed in version 1.1.0: Added ureg.


Alias to get().


key (Hashable) – Key to the UnitGenerator to evaluate. The key_converter is applied.

Return type:



Evaluated units.

New in version 21.2.0.

__setitem__(key, value)[source]#

Alias to register().

Return type:


New in version 21.2.0.


Return the UnitGenerator registered with a given key.


key (Hashable) – Key to the UnitGenerator to return. The key_converter is applied.

Return type:



Unit generator.


Evaluate UnitGenerator instance registered as key.


key (Hashable) – Key to the UnitGenerator to evaluate. The key_converter is applied.

Return type:



Evaluated units.


Evaluate all registered UnitGenerator instance.

Return type:

Dict[Hashable, Unit]


Evaluated units as a dictionary.

override(*args, **kwargs)[source]#

Temporarily override underlying unit generators. This method acts as a convenience proxy for UnitGenerator.override().

Override specifications can take multiple forms: :rtype: None

  • an arbitrary number of dictionaries can be passed as positional arguments;

  • key-value pairs may also be specified as keyword arguments.

Both approaches can be mixed.


When using the keyword argument specification, passed values will systematically be strings. Consequently, either

  • registry keys must be strings;

  • or the key_converter must provide the conversion protocol for string-valued keys.

register(key, value)[source]#

Add or update an entry in the registry. Conversion rules are applied as follows:

  • key is applied the key_converter converter;

  • value is converted to a UnitGenerator.

In addition, if interpret_str is True, value can be specified as a string. In that case, it will be converted to a pint.Unit using the unit registry returned by get_unit_registry().

Return type:



Update the registry with a dictionary.


d (Dict) – Dictionary used to apply register() for each of its key-value pairs.

Return type:


Default unit registry#


Get default unit registry.

Return type:



Set unit registry. By default, Pinttrs has its own registry.


ureg (UnitRegistry) – Unit registry.


TypeError if ureg is not a pint.UnitRegistry.

Return type:


Dictionary interpretation#

pinttr.interpret_units(d, ureg=None, inplace=False)[source]#

Interpret units in a dictionary. The dictionary is searched for matching magnitude-units field pairs. For a magnitude field with key "x", the corresponding unit field is "x_units". For each pair found, the magnitude field is attached units and converted to a pint.Quantity object. The unit field is then dropped.

If the magnitude field is already a Pint quantity, it will be converted to specified units (and conversion will fail if units are incompatible).


    "field": 1.0,
    "field_units": "m"

will be interpreted as

{"field": ureg.Quantity(1.0, "m")}


Dictionary keys must be strings.

  • d (Dict[str, Any]) – Dictionary in which units will be interpreted.

  • ureg (Optional[UnitRegistry]) – Unit registry to use for unit creation. If set to None, Pinttrs’s registered unit registry is used. See also pinttr.set_unit_registry().

  • inplace (bool) – If True, modify the dictionary in-place; otherwise, return a modified copy.

Return type:

Dict[str, Any]


A copy of d, where unit fields are interpreted using ureg to attach units to the corresponding magnitude field.

Changed in version 1.1.0: Support for converting quantity magnitude fields.

Converters [pinttr.converters]#


Create a callable f(x) returning ensure_units(x, units, convert=False).


units (Union[Unit, UnitGenerator]) – Units to ensure conversion to.

Return type:

Callable[[Any], Quantity]

Validators [pinttr.validators]#

pinttr.validators.has_compatible_units(instance, attribute, value)[source]#

Validate if value has units compatible (in the sense of units_compatible()) with attribute. Only works with unit-enabled fields created with pinttr.ib().

Utilities [pinttr.util]#

pinttr.util.always_iterable(obj, base_type=(<class 'str'>, <class 'bytes'>))[source]#

Ensure that the object it is passed is iterable.

  • If obj is iterable, return an iterator over its items.

  • If obj is not iterable, return a one-item iterable containing obj.

  • If obj is None, return an empty iterable.

By default, binary and text strings are not considered iterable. If base_type is set, objects for which isinstance(obj, base_type) returns True won’t be considered iterable.

Set base_type to None to avoid any special handling and treat objects Python considers iterable as iterable.


Copied from more_itertools.always_iterable().

pinttr.converters.ensure_units(value, default_units, convert=False)[source]#

Ensure that a value is wrapped in a Pint quantity container.

  • value (Any) – Value to ensure the wrapping of.

  • default_units (Union[Unit, Callable]) – Units to use to initialise the pint.Quantity if value is not a pint.Quantity. A callable can be passed; in this case, the applied units will be default_units().

  • convert (bool) – If True, value will also be converted to default_units if it is a pint.Quantity.

Return type:



Converted value.

Changed in version 21.1.0: Relocated from pinttr.converters to pinttr.util.

pinttr.util.units_compatible(unit1, unit2)[source]#

Check if two units are compatible. Accounts for angle units.

  • unit1 (Unit) – First unit to check for compatibility.

  • unit2 (Unit) – Second unit to check for compatibility.

Return type:



True if unit1 and unit2 have the same dimensionality, False otherwise.

Exceptions [pinttr.exceptions]#

exception pinttr.exceptions.UnitsError(units1, units2, dim1='', dim2='', extra_msg='')[source]#

Bases: DimensionalityError

Raised when encountering issues with units (can be raised even when DimensionalityError would not).

Next-generation APIs#

Pinttrs provides APIs matching attrs next-generation APIs for syntactic homogeneity.

pinttr.field(*, default=_Nothing.NOTHING, validator=_Nothing.NOTHING, repr=_Nothing.NOTHING, hash=None, init=True, metadata=None, converter=_Nothing.NOTHING, factory=None, kw_only=False, eq=None, order=None, on_setattr=_Nothing.NOTHING, units=None)[source]#

Identical to pinttr.ib(), except keyword-only and with some arguments removed.

New in version 21.3.0.