API Reference¶
Main interface¶
- pinttrs.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.Added in version 21.3.0.
Dynamic unit management¶
- class pinttrs.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.UnitorCallable) – Stored units or generator.
- __call__()[source]¶
- Return type:
- Returns:
If
unitsis apint.Unit, it is returned; ifunitsis a callable (typically, anotherUnitGenerator), the result of its evaluation will be returned.
- class pinttrs.UnitContext(registry=NOTHING, interpret_str=False, ureg=None, key_converter=<function identity>)[source]¶
An overridable registry of
UnitGeneratorobjects.This class maintains a registry of
UnitGeneratorinstances. StoredUnitGeneratorobjects can be conveniently overridden using theoverride()context manager.- Attributes / constructor arguments:
registry (Dict[Hashable,
UnitGenerator]) – Unit generator registry. Keys can be any hashable type, butstrorEnumare recommended. Defaults to an empty dictionary.Note
The initialization sequence will make repeated calls to
register()and will consequently apply the same key and value conversion rules.interpret_str (
bool) – IfTrue, attempt string-to-units interpretation when specifying unit generators asstr.ureg (Optional[
UnitRegistry]) – Unit registry used for string-to-units interpretation. IfNone, the default registry is used (seeget_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 theUnitGeneratorto evaluate. Thekey_converteris applied.- Return type:
- Returns:
Evaluated units.
Added in version 21.2.0.
- __setitem__(key, value)[source]¶
Alias to
register().- Parameters:
key (
Hashable) – Key to the registered entry.value (
Union[UnitGenerator,Unit,str]) – Object to register.
- Return type:
Added in version 21.2.0.
- deferred(key)[source]¶
Return the
UnitGeneratorregistered with a given key.- Parameters:
key (
Hashable) – Key to theUnitGeneratorto return. Thekey_converteris applied.- Return type:
- Returns:
Unit generator.
- get(key)[source]¶
Evaluate
UnitGeneratorinstance registered askey.- Parameters:
key (
Hashable) – Key to theUnitGeneratorto evaluate. Thekey_converteris applied.- Return type:
- Returns:
Evaluated units.
- get_all()[source]¶
Evaluate all registered
UnitGeneratorinstance.
- 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:
Nonean 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_convertermust 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:
keyis applied thekey_converterconverter;valueis converted to aUnitGenerator.
In addition, if
interpret_strisTrue,valuecan be specified as a string. In that case, it will be converted to apint.Unitusing the unit registry returned byget_unit_registry().- Parameters:
key (
Hashable) – Key to the registered entry.value (
Union[UnitGenerator,Unit,str]) – Object to register.
- Return type:
- update(d)[source]¶
Update the registry with a dictionary.
- Parameters:
d (
Dict) – Dictionary used to applyregister()for each of its key-value pairs.- Return type:
Default unit registry¶
- pinttrs.get_unit_registry()[source]¶
Get default unit registry. By default, Pinttrs uses the application registry). :rtype:
Union[UnitRegistry,ApplicationRegistry]Changed in version 24.1.0: The default registry is now the application registry.
- pinttrs.set_unit_registry(ureg)[source]¶
Set unit registry. By default, Pinttrs uses the application registry).
- Parameters:
ureg (
Union[UnitRegistry,ApplicationRegistry]) – Unit registry.- Raises:
TypeErrorifuregis not apint.UnitRegistry.- Return type:
Changed in version 24.1.0: The default registry is now the application registry.
Dictionary interpretation¶
- pinttrs.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 apint.Quantityobject. 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 toNone, Pinttrs’s registered unit registry is used. See alsopinttr.set_unit_registry().inplace (
bool) – IfTrue, modify the dictionary in-place; otherwise, return a modified copy.
- Return type:
- Returns:
A copy of
d, where unit fields are interpreted usinguregto attach units to the corresponding magnitude field.
Changed in version 1.1.0: Support for converting quantity magnitude fields.
Converters [pinttrs.converters]¶
- pinttrs.converters.ensure_units(maybe_value=NOTHING, *, default_units, convert=False)[source]¶
Ensure that a value is wrapped in a Pint quantity container.
This converter can be used in two modes:
Immediate mode: Pass a value to convert it directly.
Deferred mode: Omit the value to get a converter function.
- Parameters:
maybe_value (
Any) – Value to ensure the wrapping of. If not supplied, this function returns a converter with the signaturef(x: Any) -> Anythat is effectivelyfunctools.partial(ensure_units, default_units=default_units, convert=convert).default_units (
Union[Unit,Callable]) – Units to use to initialize thepint.Quantityifmaybe_valueis not apint.Quantity. A callable can be passed; in this case, the applied units will bedefault_units().convert (
bool) – IfTrue,maybe_valuewill also be converted todefault_unitsif it is apint.Quantity.
- Return type:
- Returns:
Converted
maybe_valueif specified; otherwise, a converter function.
Examples
Immediate mode. Convert a value directly:
>>> ensure_units(100.0, default_units=ureg.m) <Quantity(100.0, 'meter')>
By default, quantities with units are passed through unchanged:
>>> ensure_units(100.0 * ureg.km, default_units=ureg.m) <Quantity(100.0, 'kilometer')>
Set
convert=Trueto force conversion to the default units:>>> ensure_units(100.0 * ureg.km, default_units=ureg.m, convert=True) <Quantity(100000.0, 'meter')>
Deferred mode: Create a converter function:
>>> converter = ensure_units(default_units=ureg.km) >>> converter(5.0) <Quantity(5.0, 'kilometer')> >>> converter(100.0 * ureg.m) <Quantity(100.0, 'meter')>
This is particularly useful with attrs:
>>> @attrs.define ... class Circle: ... radius = attrs.field(converter=ensure_units (default_units=ureg.m)) >>> Circle(radius=100.0) Circle(radius=<Quantity(100.0, 'meter')>) >>> Circle(radius=5.0 * ureg.km) Circle(radius=<Quantity(5.0, 'kilometer')>)
Changed in version 21.1.0: Relocated from
pinttr.converterstopinttr.util.Changed in version 26.1.0: Relocated again from
pinttr.utiltopinttr.converters. The previous is kept as an alias and is deprecated.Changed in version 26.1.0: The first argument is now optional, which allows both deferred and immediate executions.
- pinttrs.converters.to_quantity(value)[source]¶
Attempts turning an object into a Pint quantity. Unsupported types are simply passed through.
This converter is useful for loading data from serialized formats (JSON, YAML) or working with xarray DataArrays that follow CF conventions.
The following types are supported:
dict(or, more generally, mappings): the magnitude (resp. units) must be supplied as thevalue,magnitudeormkeys (resp.units,unitoru).xarray.DataArray: the magnitude is the underlying data array (converted to a NumPy array) and units are read from theunitsattribute. If theunitsattribute is missing, the DataArray is returned unchanged. If the xarray dependency is not installed, conversion is skipped.
Warning
This converter uses the global unit registry from
get_unit_registry().Extra keys in dictionaries will raise a
ValueError.
- Parameters:
value (
Any) – Object to attempt conversion on.- Raises:
ValueError – When converting a dictionary, if a magnitude or unit key is missing.
ValueError – When converting a dictionary, if unhandled keys are supplied.
- Return type:
Examples
Converting dictionaries: Useful for loading from JSON or YAML files:
>>> to_quantity({"value": 1.0, "units": "m"}) <Quantity(1.0, 'meter')> >>> to_quantity({"magnitude": 2.5, "units": "km"}) <Quantity(2.5, 'kilometer')>
Shorter key names are also supported:
>>> to_quantity({"m": 100.0, "u": "cm"}) <Quantity(100.0, 'centimeter')>
Unsupported types pass through unchanged:
>>> to_quantity(42.0) 42.0 >>> to_quantity("text") 'text'
Converting xarray DataArrays: Extracts data and units from DataArrays following CF conventions (requires xarray):
>>> data = xr.DataArray([1.0, 2.0, 3.0], attrs={"units": "m"}) >>> to_quantity(data) <Quantity([1. 2. 3.], 'meter')>
DataArrays without units are passed through:
>>> data = xr.DataArray([1.0, 2.0]) >>> to_quantity(data) <xarray.DataArray (dim_0: 2)>...
Added in version 26.1.0: When converting dictionaries, units can be specified using the
unitfield.
- pinttrs.converters.to_units(units)[source]¶
Create a callable
f(x)returningensure_units(x, units, convert=False).- Parameters:
units (
Union[Unit,UnitGenerator]) – Units to ensure conversion to.- Return type:
Deprecated since version 26.1.0: Prefer
pinttrs.converters.ensure_units()in its deferred form.
Validators [pinttrs.validators]¶
- pinttrs.validators.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
pinttrs.field()orpinttr.attrib().- 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.
Utilities [pinttrs.util]¶
- pinttrs.util.always_iterable(obj, base_type=(<class 'str'>, <class 'bytes'>))[source]¶
Ensure that the object it is passed is iterable.
If
objis iterable, return an iterator over its items.If
objis not iterable, return a one-item iterable containingobj.If
objisNone, return an empty iterable.
By default, binary and text strings are not considered iterable. If
base_typeis set, objects for whichisinstance(obj, base_type)returnsTruewon’t be considered iterable.Set
base_typetoNoneto avoid any special handling and treat objects Python considers iterable as iterable.Note
Copied from
more_itertools.always_iterable().
- pinttrs.util.ensure_units(maybe_value=NOTHING, *, default_units, convert=False)[source]¶
Compatibility alias to
pinttrs.converters.ensure_units(). :rtype:AnyDeprecated since version 26.1.0: Prefer
pinttrs.converters.ensure_units().
Exceptions [pinttrs.exceptions]¶
- exception pinttrs.exceptions.UnitsError(units1, units2, dim1='', dim2='', extra_msg='')[source]¶
Bases:
DimensionalityErrorRaised when encountering issues with units (can be raised even when
DimensionalityErrorwould not).