API Reference#
Main interface#
- pinttrs.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.
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.Unit
orCallable
) – Stored units or generator.
- __call__()[source]#
- Return type:
- Returns:
If
units
is apint.Unit
, it is returned; ifunits
is a callable (typically, anotherUnitGenerator
), the result of its evaluation will be returned.
- class pinttrs.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. StoredUnitGenerator
objects can be conveniently overridden using theoverride()
context manager.- Attributes / constructor arguments:
registry (Dict[Hashable,
UnitGenerator
]) – Unit generator registry. Keys can be any hashable type, butstr
orEnum
are 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 theUnitGenerator
to evaluate. Thekey_converter
is applied.- Return type:
- Returns:
Evaluated units.
New 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:
New in version 21.2.0.
- deferred(key)[source]#
Return the
UnitGenerator
registered with a given key.- Parameters:
key (
Hashable
) – Key to theUnitGenerator
to return. Thekey_converter
is applied.- Return type:
- Returns:
Unit generator.
- get(key)[source]#
Evaluate
UnitGenerator
instance registered askey
.- Parameters:
key (
Hashable
) – Key to theUnitGenerator
to evaluate. Thekey_converter
is applied.- Return type:
- Returns:
Evaluated units.
- get_all()[source]#
Evaluate all registered
UnitGenerator
instance.
- 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.
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.
- register(key, value)[source]#
Add or update an entry in the registry. Conversion rules are applied as follows:
key
is applied thekey_converter
converter;value
is converted to aUnitGenerator
.
In addition, if
interpret_str
isTrue
,value
can be specified as a string. In that case, it will be converted to apint.Unit
using 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:
TypeError
ifureg
is 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.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 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 usingureg
to 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
value
has 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
obj
is iterable, return an iterator over its items.If
obj
is not iterable, return a one-item iterable containingobj
.If
obj
isNone
, return an empty iterable.
By default, binary and text strings are not considered iterable. If
base_type
is set, objects for whichisinstance(obj, base_type)
returnsTrue
won’t be considered iterable.Set
base_type
toNone
to 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.Quantity
ifvalue
is not apint.Quantity
. A callable can be passed; in this case, the applied units will bedefault_units()
.convert (
bool
) – IfTrue
,value
will also be converted todefault_units
if it is apint.Quantity
.
- Return type:
- Returns:
Converted
value
.
Changed in version 21.1.0: Relocated from
pinttr.converters
topinttr.util
.
Exceptions [pinttrs.exceptions
]#
- exception pinttrs.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).