API Reference#

Main interface#

pinttr.ib(default=NOTHING, validator=NOTHING, repr=NOTHING, cmp=None, hash=None, init=True, metadata=None, type=None, converter=NOTHING, factory=None, kw_only=False, eq=None, order=None, on_setattr=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.

Parameters
  • 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

UnitContext

Attributes / constructor arguments

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

__call__()[source]#
Return type

Unit

Returns

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.

override(units)[source]#

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

Parameters

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

Return type

None

class pinttr.UnitContext(registry=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.

    Note

    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.

__getitem__(key)[source]#

Alias to get().

Parameters

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

Return type

Unit

Returns

Evaluated units.

New in version 21.2.0.

__setitem__(key, value)[source]#

Alias to register().

Parameters

New in version 21.2.0.

Return type

None

deferred(key)[source]#

Return the UnitGenerator registered with a given key.

Parameters

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

Return type

UnitGenerator

Returns

Unit generator.

get(key)[source]#

Evaluate UnitGenerator instance registered as key.

Parameters

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

Return type

Unit

Returns

Evaluated units.

get_all()[source]#

Evaluate all registered UnitGenerator instance.

Return type

Dict[Hashable, Unit]

Returns

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:

  • 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.

Note

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.

Return type

None

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().

Parameters
Return type

None

update(d)[source]#

Update the registry with a dictionary.

Parameters

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

Return type

None

Default unit registry#

pinttr.get_unit_registry()[source]#

Get default unit registry.

Return type

UnitRegistry

pinttr.set_unit_registry(ureg)[source]#

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

Parameters

ureg (UnitRegistry) – Unit registry.

Raises

TypeError if ureg is not a pint.UnitRegistry.

Return type

None

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).

Example

{
    "field": 1.0,
    "field_units": "m"
}

will be interpreted as

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

Warning

Dictionary keys must be strings.

Parameters
  • 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]

Returns

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]#

pinttr.converters.to_units(units)[source]#

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

Parameters

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.

Note

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.

Parameters
  • 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

Quantity

Returns

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.

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

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

Return type

bool

Returns

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, 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]#

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

New in version 21.3.0.