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().
- 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.to_units(units)[source]¶
Create a callable
f(x)returningensure_units(x, units, convert=False).
Validators [pinttrs.validators]¶
- pinttrs.validators.has_compatible_units(instance, attribute, value)[source]¶
Validate if
valuehas units compatible (in the sense ofunits_compatible()) withattribute. Only works with unit-enabled fields created withpinttr.ib().
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.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 initialize thepint.Quantityifvalueis not apint.Quantity. A callable can be passed; in this case, the applied units will bedefault_units().convert (
bool) – IfTrue,valuewill also be converted todefault_unitsif it is apint.Quantity.
- Return type:
- Returns:
Converted
value.
Changed in version 21.1.0: Relocated from
pinttr.converterstopinttr.util.
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).