Developer reference

All Modules

pint

Pint is Python module/package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.Context(name: Optional[str] = None, aliases: Tuple[str, ...] = (), defaults: Optional[dict] = None)[source]

A specialized container that defines transformation functions from one dimension to another. Each Dimension are specified using a UnitsContainer. Simple transformation are given with a function taking a single parameter.

Conversion functions may take optional keyword arguments and the context can have default values for these arguments.

Additionally, a context may host redefinitions.

A redefinition must be performed among units that already exist in the registry. It cannot change the dimensionality of a unit. The symbol and aliases are automatically inherited from the registry.

See ContextDefinition for the definition file syntax.

Parameters
  • name (str or None, optional) – Name of the context (must be unique within the registry). Use None for anonymous Context. (Default value = None).

  • aliases (iterable of str) – Other names for the context.

  • defaults (None or dict) – Maps variable names to values.

Example

>>> from pint.util import UnitsContainer
>>> from pint import Context, UnitRegistry
>>> ureg = UnitRegistry()
>>> timedim = UnitsContainer({'[time]': 1})
>>> spacedim = UnitsContainer({'[length]': 1})
>>> def time_to_len(ureg, time):
...     'Time to length converter'
...     return 3. * time
>>> c = Context()
>>> c.add_transformation(timedim, spacedim, time_to_len)
>>> c.transform(timedim, spacedim, ureg, 2)
6.0
>>> def time_to_len_indexed(ureg, time, n=1):
...     'Time to length converter, n is the index of refraction of the material'
...     return 3. * time / n
>>> c = Context(defaults={'n':3})
>>> c.add_transformation(timedim, spacedim, time_to_len_indexed)
>>> c.transform(timedim, spacedim, ureg, 2)
2.0
>>> c.redefine("pound = 0.5 kg")
add_transformation(src, dst, func) None[source]

Add a transformation function to the context.

defaults

Maps defaults variable names to values

classmethod from_context(context: Context, **defaults) Context[source]

Creates a new context that shares the funcs dictionary with the original context. The default values are copied from the original context and updated with the new defaults.

If defaults is empty, return the same context.

Parameters
  • context (pint.Context) – Original context.

  • **defaults

Return type

pint.Context

funcs

Maps (src, dst) -> transformation function

hashable() Tuple[Optional[str], Tuple[str, ...], frozenset, frozenset, tuple][source]

Generate a unique hashable and comparable representation of self, which can be used as a key in a dict. This class cannot define __hash__ because it is mutable, and the Python interpreter does cache the output of __hash__.

Return type

tuple

redefine(definition: str) None[source]

Override the definition of a unit in the registry.

Parameters

definition (str) – <unit> = <new definition>``, e.g. pound = 0.5 kg

relation_to_context

Maps (src, dst) -> self Used as a convenience dictionary to be composed by ContextChain

remove_transformation(src, dst) None[source]

Add a transformation function to the context.

transform(src, dst, registry, value)[source]

Transform a value.

exception pint.DefinitionSyntaxError(msg, *, filename=None, lineno=None)[source]

Raised when a textual definition has a syntax error.

exception pint.DimensionalityError(units1, units2, dim1='', dim2='', *, extra_msg='')[source]

Raised when trying to convert between incompatible units.

exception pint.LogarithmicUnitCalculusError[source]

Raised on inappropriate operations with logarithmic units.

class pint.Measurement(value, error, units=<object object>)
exception pint.OffsetUnitCalculusError[source]

Raised on ambiguous operations with offset units.

exception pint.PintError[source]

Base exception for all Pint errors.

exception pint.RedefinitionError(name, definition_type, *, filename=None, lineno=None)[source]

Raised when a unit or prefix is redefined.

exception pint.UndefinedUnitError(*unit_names)[source]

Raised when the units are not defined in the unit registry.

class pint.Unit(*args, **kwargs)
class pint.UnitRegistry(*args, **kwargs)[source]

The unit registry stores the definitions and relationships between units.

Parameters
  • filename – path of the units definition file to load or line-iterable object. Empty to load the default definition file. None to leave the UnitRegistry empty.

  • force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray.

  • force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray.

  • default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts.

  • autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their plain units in multiplicative context. If False no conversion happens.

  • on_redefinition (str) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’

  • auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations.

  • preprocessors – list of callables which are iteratively ran on any input expression or unit string

  • fmt_locale (Optional[Locale]) – locale identifier string, used in format_babel. Default to None

  • case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)

  • cache_folder (str or pathlib.Path or None, optional) – Specify the folder in which cache files are saved and loaded from. If None, the cache is disabled. (default)

class Group(*args, **kwargs)
class Measurement(value, error, units=<object object>)
class System(*args, **kwargs)
class Unit(*args, **kwargs)
check(*args: Optional[Union[str, UnitsContainer, Unit]]) Callable[[F], F]

Decorator to for quantity type checking for function inputs.

Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.

The wrapper function raises:
  • pint.DimensionalityError if an argument doesn’t match the required dimensions.

uregUnitRegistry

a UnitRegistry instance.

argsstr or UnitContainer or None

Dimensions of each of the input arguments. Use None to skip argument conversion.

Returns

the wrapped function.

Return type

callable

Raises
  • TypeError – If the number of given dimensions does not match the number of function parameters.

  • ValueError – If the any of the provided dimensions cannot be parsed as a dimension.

pi_theorem(quantities)[source]

Builds dimensionless quantities using the Buckingham π theorem

Parameters

quantities (dict) – mapping between variable name and units

Returns

a list of dimensionless quantities expressed as dicts

Return type

list

setup_matplotlib(enable: bool = True) None[source]

Set up handlers for matplotlib’s unit support.

Parameters

enable (bool) – whether support should be enabled or disabled (Default value = True)

wraps(ret: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], args: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], strict: bool = True) Callable[[Callable[..., T]], Callable[..., Quantity[T]]]

Wraps a function to become pint-aware.

Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.

The value returned by the wrapped function will be converted to the units specified in ret.

Parameters
  • ureg (pint.UnitRegistry) – a UnitRegistry instance.

  • ret (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the return values. Use None to skip argument conversion.

  • args (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.

  • strict (bool) – Indicates that only quantities are accepted. (Default value = True)

Returns

the wrapper function.

Return type

callable

Raises

TypeError – if the number of given arguments does not match the number of function parameters. if any of the provided arguments is not a unit a string or Quantity

exception pint.UnitStrippedWarning[source]
pint.formatter(items, as_ratio=True, single_denominator=False, product_fmt=' * ', division_fmt=' / ', power_fmt='{} ** {}', parentheses_fmt='({0})', exp_call=<function <lambda>>, locale=None, babel_length='long', babel_plural_form='one', sort=True)[source]

Format a list of (name, exponent) pairs.

Parameters
  • items (list) – a list of (name, exponent) pairs.

  • as_ratio (bool, optional) – True to display as ratio, False as negative powers. (Default value = True)

  • single_denominator (bool, optional) – all with terms with negative exponents are collected together. (Default value = False)

  • product_fmt (str) – the format used for multiplication. (Default value = ” * “)

  • division_fmt (str) – the format used for division. (Default value = ” / “)

  • power_fmt (str) – the format used for exponentiation. (Default value = “{} ** {}”)

  • parentheses_fmt (str) – the format used for parenthesis. (Default value = “({0})”)

  • locale (str) – the locale object as defined in babel. (Default value = None)

  • babel_length (str) – the length of the translated unit, as defined in babel cldr. (Default value = “long”)

  • babel_plural_form (str) – the plural form, calculated as defined in babel. (Default value = “one”)

  • exp_call (callable) – (Default value = lambda x: f”{x:n}”)

  • sort (bool, optional) – True to sort the formatted units alphabetically (Default value = True)

Returns

the formula as a string.

Return type

str

pint.get_application_registry()[source]

Return the application registry. If set_application_registry() was never invoked, return a registry built using defaults_en.txt embedded in the pint package.

Return type

pint.UnitRegistry

pint.pi_theorem(quantities, registry=None)[source]

Builds dimensionless quantities using the Buckingham π theorem

Parameters
  • quantities (dict) – mapping between variable name and units

  • registry – (Default value = None)

Returns

a list of dimensionless quantities expressed as dicts

Return type

type

pint.register_unit_format(name)[source]

register a function as a new format for units

The registered function must have a signature of:

def new_format(unit, registry, **options):
    pass
Parameters

name (str) – The name of the new format (to be used in the format mini-language). A error is raised if the new format would overwrite a existing format.

Examples

@pint.register_unit_format("custom")
def format_custom(unit, registry, **options):
    result = "<formatted unit>"  # do the formatting
    return result

ureg = pint.UnitRegistry()
u = ureg.m / ureg.s ** 2
f"{u:custom}"
pint.set_application_registry(registry)[source]

Set the application registry, which is used for unpickling operations and when invoking pint.Quantity or pint.Unit directly.

Parameters

registry (pint.UnitRegistry) –

pint.babel

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.compat

Compatibility layer.

copyright

2013 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

exception pint.compat.BehaviorChangeWarning[source]
pint.compat.eq(lhs, rhs, check_all: bool)[source]

Comparison of scalars and arrays.

Parameters
  • lhs (object) – left-hand side

  • rhs (object) – right-hand side

  • check_all (bool) – if True, reduce sequence to single bool; return True if all the elements are equal.

Return type

bool or array_like of bool

pint.compat.is_duck_array_type(cls) bool[source]

Check if the type object represents a (non-Quantity) duck array type.

Parameters

cls (class) –

Return type

bool

pint.compat.is_upcast_type(other) bool[source]

Check if the type object is a upcast type using preset list.

Parameters

other (object) –

Return type

bool

pint.compat.isnan(obj, check_all: bool)[source]

Test for NaN or NaT

Parameters
  • obj (object) – scalar or vector

  • check_all (bool) – if True, reduce sequence to single bool; return True if any of the elements are NaN.

Returns

  • bool or array_like of bool.

  • Always return False for non-numeric types.

pint.compat.zero_or_nan(obj, check_all: bool)[source]

Test if obj is zero, NaN, or NaT

Parameters
  • obj (object) – scalar or vector

  • check_all (bool) – if True, reduce sequence to single bool; return True if all the elements are zero, NaN, or NaT.

Returns

  • bool or array_like of bool.

  • Always return False for non-numeric types.

pint.converters

Functions and classes related to unit conversions.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.converters.Converter[source]

Base class for value converters.

pint.definitions

Functions and classes related to unit definitions.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.definitions.Definition(name: str, defined_symbol: Optional[str], aliases: Tuple[str, ...], converter: Optional[Union[Callable, Converter]])[source]

Base class for definitions.

Parameters
  • name (str) – Canonical name of the unit/prefix/etc.

  • defined_symbol (str or None) – A short name or symbol for the definition.

  • aliases (iterable of str) – Other names for the unit/prefix/etc.

  • converter (callable or Converter or None) –

classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) Definition[source]

Parse a definition.

Parameters
Return type

Definition or subclass of Definition

class pint.definitions.PreprocessedDefinition(name: str, symbol: Optional[str], aliases: Tuple[str, ...], value: str, rhs_parts: Tuple[str, ...])[source]

Splits a definition into the constitutive parts.

A definition is given as a string with equalities in a single line:

---------------> rhs
a = b = c = d = e
|   |   |   -------> aliases (optional)
|   |   |
|   |   -----------> symbol (use "_" for no symbol)
|   |
|   ---------------> value
|
-------------------> name

pint.errors

Functions and classes related to unit definitions and conversions.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

exception pint.errors.DefinitionSyntaxError(msg, *, filename=None, lineno=None)[source]

Raised when a textual definition has a syntax error.

exception pint.errors.DimensionalityError(units1, units2, dim1='', dim2='', *, extra_msg='')[source]

Raised when trying to convert between incompatible units.

exception pint.errors.LogarithmicUnitCalculusError[source]

Raised on inappropriate operations with logarithmic units.

exception pint.errors.OffsetUnitCalculusError[source]

Raised on ambiguous operations with offset units.

exception pint.errors.PintError[source]

Base exception for all Pint errors.

exception pint.errors.PintTypeError[source]
exception pint.errors.RedefinitionError(name, definition_type, *, filename=None, lineno=None)[source]

Raised when a unit or prefix is redefined.

exception pint.errors.UndefinedUnitError(*unit_names)[source]

Raised when the units are not defined in the unit registry.

exception pint.errors.UnitStrippedWarning[source]

pint.formatter

Format units for pint.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.formatting.formatter(items, as_ratio=True, single_denominator=False, product_fmt=' * ', division_fmt=' / ', power_fmt='{} ** {}', parentheses_fmt='({0})', exp_call=<function <lambda>>, locale=None, babel_length='long', babel_plural_form='one', sort=True)[source]

Format a list of (name, exponent) pairs.

Parameters
  • items (list) – a list of (name, exponent) pairs.

  • as_ratio (bool, optional) – True to display as ratio, False as negative powers. (Default value = True)

  • single_denominator (bool, optional) – all with terms with negative exponents are collected together. (Default value = False)

  • product_fmt (str) – the format used for multiplication. (Default value = ” * “)

  • division_fmt (str) – the format used for division. (Default value = ” / “)

  • power_fmt (str) – the format used for exponentiation. (Default value = “{} ** {}”)

  • parentheses_fmt (str) – the format used for parenthesis. (Default value = “({0})”)

  • locale (str) – the locale object as defined in babel. (Default value = None)

  • babel_length (str) – the length of the translated unit, as defined in babel cldr. (Default value = “long”)

  • babel_plural_form (str) – the plural form, calculated as defined in babel. (Default value = “one”)

  • exp_call (callable) – (Default value = lambda x: f”{x:n}”)

  • sort (bool, optional) – True to sort the formatted units alphabetically (Default value = True)

Returns

the formula as a string.

Return type

str

pint.formatting.register_unit_format(name)[source]

register a function as a new format for units

The registered function must have a signature of:

def new_format(unit, registry, **options):
    pass
Parameters

name (str) – The name of the new format (to be used in the format mini-language). A error is raised if the new format would overwrite a existing format.

Examples

@pint.register_unit_format("custom")
def format_custom(unit, registry, **options):
    result = "<formatted unit>"  # do the formatting
    return result

ureg = pint.UnitRegistry()
u = ureg.m / ureg.s ** 2
f"{u:custom}"
pint.formatting.siunitx_format_unit(units, registry)[source]

Returns LaTeX code for the unit that can be put into an siunitx command.

pint.matplotlib

Functions and classes related to working with Matplotlib’s support for plotting with units.

copyright

2017 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.matplotlib.PintAxisInfo(units)[source]

Support default axis and tick labeling and default limits.

class pint.matplotlib.PintConverter(registry)[source]

Implement support for pint within matplotlib’s unit conversion framework.

static axisinfo(unit, axis)[source]

Return axis information for this particular unit.

convert(value, unit, axis)[source]

Convert :Quantity instances for matplotlib to use.

static default_units(x, axis)[source]

Get the default unit to use for the given combination of unit and axis.

pint.matplotlib.setup_matplotlib_handlers(registry, enable)[source]

Set up matplotlib’s unit support to handle units from a registry.

Parameters
  • registry (pint.UnitRegistry) – The registry that will be used.

  • enable (bool) – Whether support should be enabled or disabled.

pint.pint_eval

An expression evaluator to be used as a safe replacement for builtin eval.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.pint_eval.EvalTreeNode(left, operator=None, right=None)[source]

Single node within an evaluation tree

left + operator + right –> binary op left + operator –> unary op left + right –> implicit op left –> single value

evaluate(define_op, bin_op=None, un_op=None)[source]

Evaluate node.

Parameters
  • define_op (callable) – Translates tokens into objects.

  • bin_op (dict or None, optional) – (Default value = _BINARY_OPERATOR_MAP)

  • un_op (dict or None, optional) – (Default value = _UNARY_OPERATOR_MAP)

pint.pint_eval.build_eval_tree(tokens: Iterable[tokenize.TokenInfo], op_priority=None, index=0, depth=0, prev_op=None) tuple[EvalTreeNode | None, int] | EvalTreeNode[source]

Build an evaluation tree from a set of tokens.

Params: Index, depth, and prev_op used recursively, so don’t touch. Tokens is an iterable of tokens from an expression to be evaluated.

Transform the tokens from an expression into a recursive parse tree, following order of operations. Operations can include binary ops (3 + 4), implicit ops (3 kg), or unary ops (-1).

General Strategy: 1) Get left side of operator 2) If no tokens left, return final result 3) Get operator 4) Use recursion to create tree starting at token on right side of operator (start at step #1) 4.1) If recursive call encounters an operator with lower or equal priority to step #2, exit recursion 5) Combine left side, operator, and right side into a new left side 6) Go back to step #2

pint.registry

Defines the UnitRegistry, a class to contain units and their relations.

This registry contains all pint capabilities, but you can build your customized registry by picking only the features that you actually need.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.registry.ApplicationRegistry(registry)[source]

A wrapper class used to distribute changes to the application registry.

get()[source]

Get the wrapped registry

set(new_registry)[source]

Set the new registry

Parameters

new_registry (ApplicationRegistry or LazyRegistry or UnitRegistry) – The new registry.

See also

set_application_registry

class pint.registry.UnitRegistry(*args, **kwargs)[source]

The unit registry stores the definitions and relationships between units.

Parameters
  • filename – path of the units definition file to load or line-iterable object. Empty to load the default definition file. None to leave the UnitRegistry empty.

  • force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray.

  • force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray.

  • default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts.

  • autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their plain units in multiplicative context. If False no conversion happens.

  • on_redefinition (str) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’

  • auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations.

  • preprocessors – list of callables which are iteratively ran on any input expression or unit string

  • fmt_locale (Optional[Locale]) – locale identifier string, used in format_babel. Default to None

  • case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)

  • cache_folder (str or pathlib.Path or None, optional) – Specify the folder in which cache files are saved and loaded from. If None, the cache is disabled. (default)

class Group(*args, **kwargs)
class Measurement(value, error, units=<object object>)
class System(*args, **kwargs)
class Unit(*args, **kwargs)
check(*args: Optional[Union[str, UnitsContainer, Unit]]) Callable[[F], F]

Decorator to for quantity type checking for function inputs.

Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.

The wrapper function raises:
  • pint.DimensionalityError if an argument doesn’t match the required dimensions.

uregUnitRegistry

a UnitRegistry instance.

argsstr or UnitContainer or None

Dimensions of each of the input arguments. Use None to skip argument conversion.

Returns

the wrapped function.

Return type

callable

Raises
  • TypeError – If the number of given dimensions does not match the number of function parameters.

  • ValueError – If the any of the provided dimensions cannot be parsed as a dimension.

pi_theorem(quantities)[source]

Builds dimensionless quantities using the Buckingham π theorem

Parameters

quantities (dict) – mapping between variable name and units

Returns

a list of dimensionless quantities expressed as dicts

Return type

list

setup_matplotlib(enable: bool = True) None[source]

Set up handlers for matplotlib’s unit support.

Parameters

enable (bool) – whether support should be enabled or disabled (Default value = True)

wraps(ret: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], args: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], strict: bool = True) Callable[[Callable[..., T]], Callable[..., Quantity[T]]]

Wraps a function to become pint-aware.

Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.

The value returned by the wrapped function will be converted to the units specified in ret.

Parameters
  • ureg (pint.UnitRegistry) – a UnitRegistry instance.

  • ret (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the return values. Use None to skip argument conversion.

  • args (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.

  • strict (bool) – Indicates that only quantities are accepted. (Default value = True)

Returns

the wrapper function.

Return type

callable

Raises

TypeError – if the number of given arguments does not match the number of function parameters. if any of the provided arguments is not a unit a string or Quantity

pint.registry_helpers

Miscellaneous methods of the registry written as separate functions.

copyright

2016 by Pint Authors, see AUTHORS for more details..

license

BSD, see LICENSE for more details.

pint.registry_helpers.check(ureg: UnitRegistry, *args: Optional[Union[str, UnitsContainer, Unit]]) Callable[[F], F][source]

Decorator to for quantity type checking for function inputs.

Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.

The wrapper function raises:
  • pint.DimensionalityError if an argument doesn’t match the required dimensions.

uregUnitRegistry

a UnitRegistry instance.

argsstr or UnitContainer or None

Dimensions of each of the input arguments. Use None to skip argument conversion.

Returns

the wrapped function.

Return type

callable

Raises
  • TypeError – If the number of given dimensions does not match the number of function parameters.

  • ValueError – If the any of the provided dimensions cannot be parsed as a dimension.

pint.registry_helpers.wraps(ureg: UnitRegistry, ret: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], args: Union[str, 'Unit', Iterable[Union[str, 'Unit', None]], None], strict: bool = True) Callable[[Callable[..., T]], Callable[..., Quantity[T]]][source]

Wraps a function to become pint-aware.

Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.

The value returned by the wrapped function will be converted to the units specified in ret.

Parameters
  • ureg (pint.UnitRegistry) – a UnitRegistry instance.

  • ret (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the return values. Use None to skip argument conversion.

  • args (str, pint.Unit, or iterable of str or pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.

  • strict (bool) – Indicates that only quantities are accepted. (Default value = True)

Returns

the wrapper function.

Return type

callable

Raises

TypeError – if the number of given arguments does not match the number of function parameters. if any of the provided arguments is not a unit a string or Quantity

pint.util

Miscellaneous functions for pint.

copyright

2016 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.util.BlockIterator(line_iterator)[source]

Like SourceIterator but stops when it finds @end’ It also raises an error if another ‘@’ directive is found inside.

class pint.util.ParserHelper(scale=1, *args, **kwargs)[source]

The ParserHelper stores in place the product of variables and their respective exponent and implements the corresponding operations.

ParserHelper is a read-only mapping. All operations (even in place ones)

Returns

WARNING : The hash value used does not take into account the scale attribute so be careful if you use it as a dict key and then two unequal object can have the same hash.

Return type

type

classmethod from_string(input_string, non_int_type=<class 'float'>)[source]

Parse linear expression mathematical units and return a quantity object.

Parameters

input_string

classmethod from_word(input_word, non_int_type=<class 'float'>)[source]

Creates a ParserHelper object with a single variable with exponent one.

Equivalent to: ParserHelper({‘word’: 1})

Parameters

input_word

class pint.util.PrettyIPython[source]

Mixin to add pretty-printers for IPython

class pint.util.SharedRegistryObject(*args, **kwargs)[source]

Base class for object keeping a reference to the registree.

Such object are for now Quantity and Unit, in a number of places it is that an object from this class has a ‘_units’ attribute.

class pint.util.SourceIterator(sequence, filename=None, is_resource=False)[source]

Iterator to facilitate reading the definition files.

Accepts any sequence (like a list of lines, a file or another SourceIterator)

The iterator yields the line number and line (skipping comments and empty lines) and stripping white spaces.

for lineno, line in SourceIterator(sequence):

# do something here

block_iter()[source]

Iterate block including header.

class pint.util.UnitsContainer(*args, **kwargs)[source]

The UnitsContainer stores the product of units and their respective exponent and implements the corresponding operations.

UnitsContainer is a read-only mapping. All operations (even in place ones)

Return type

type

remove(keys)[source]

Create a new UnitsContainer purged from given keys.

Parameters

keys

rename(oldkey, newkey)[source]

Create a new UnitsContainer in which an entry has been renamed.

Parameters
  • oldkey

  • newkey

pint.util.build_dependent_class(registry_class, class_name: str, attribute_name: str) Type[source]

Creates a class specifically for the given registry that subclass all the classes named by the registry bases in a specific attribute

  1. List the ‘attribute_name’ attribute for each of the bases of the registry class.

  2. Use this list as bases for the new class

  3. Add the provided registry as the class registry.

pint.util.column_echelon_form(matrix, ntype=<class 'fractions.Fraction'>, transpose_result=False)[source]

Calculates the column echelon form using Gaussian elimination.

Parameters
  • matrix – a 2D matrix as nested list.

  • ntype – the numerical type to use in the calculation. (Default value = Fraction)

  • transpose_result – indicates if the returned matrix should be transposed. (Default value = False)

Returns

column echelon form, transformed identity matrix, swapped rows

Return type

type

pint.util.create_class_with_registry(registry, base_class) Type[source]

Create new class inheriting from base_class and filling _REGISTRY class attribute with an actual instanced registry.

pint.util.getattr_maybe_raise(self, item)[source]

Helper function invoked at start of all overridden __getattr__.

Raise AttributeError if the user tries to ask for a _ or __ attribute, unless it is immediately followed by a number, to enable units encompassing constants, such as L / _100km.

Parameters

item (string) – Item to be found.

pint.util.infer_base_unit(unit_like: Union[UnitLike, Quantity], registry: Optional[UnitRegistry] = None) UnitsContainer[source]

Given a Quantity or UnitLike, give the UnitsContainer for it’s plain units.

Parameters
  • unit_like (Union[UnitLike, Quantity]) – Quantity or Unit to infer the plain units from.

  • registry (Optional[UnitRegistry]) – If provided, uses the registry’s UnitsContainer and parse_unit_name. If None, uses the registry attached to unit_like.

Return type

UnitsContainer

Raises

ValueError – The unit_like did not reference a registry, and no registry was provided.

pint.util.iterable(y) bool[source]

Check whether or not an object can be iterated over.

Vendored from numpy under the terms of the BSD 3-Clause License. (Copyright (c) 2005-2019, NumPy Developers.)

Parameters
  • value – Input object.

  • type – object

  • y

pint.util.matrix_to_string(matrix, row_headers=None, col_headers=None, fmtfun=<function <lambda>>)[source]

Takes a 2D matrix (as nested list) and returns a string.

Parameters
  • matrix

  • row_headers – (Default value = None)

  • col_headers – (Default value = None)

  • fmtfun – (Default value = lambda x: str(int(x)))

pint.util.pi_theorem(quantities, registry=None)[source]

Builds dimensionless quantities using the Buckingham π theorem

Parameters
  • quantities (dict) – mapping between variable name and units

  • registry – (Default value = None)

Returns

a list of dimensionless quantities expressed as dicts

Return type

type

pint.util.sized(y) bool[source]

Check whether or not an object has a defined length.

Parameters
  • value – Input object.

  • type – object

  • y

pint.util.solve_dependencies(dependencies)[source]

Solve a dependency graph.

Parameters

dependencies – dependency dictionary. For each key, the value is an iterable indicating its dependencies.

Returns

iterator of sets, each containing keys of independents tasks dependent only of the previous tasks in the list.

Return type

type

pint.util.to_units_container(unit_like: Union[UnitLike, Quantity], registry: Optional[UnitRegistry] = None) UnitsContainer[source]

Convert a unit compatible type to a UnitsContainer.

Parameters
  • unit_like

  • registry – (Default value = None)

pint.util.transpose(matrix)[source]

Takes a 2D matrix (as nested list) and returns the transposed version.

Parameters

matrix

class pint.util.udict[source]

Custom dict implementing __missing__.

copy() a shallow copy of D[source]

Facets

pint.facets.plain

Base implementation for registry, units and quantities.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.nonmultiplicative

Adds pint the capability to handle nonmultiplicative units: - offset - logarithmic

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.formatting

Adds pint the capability to format quantities and units into string.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.numpy

Adds pint the capability to interoperate with NumPy

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.numpy

Adds pint the capability to interoperate with Dask

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

class pint.facets.dask.DaskRegistry(*args, **kwargs)[source]
class Quantity(value: str, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: Sequence, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: PlainQuantity[Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)

pint.facets.measurement

Adds pint the capability to handle measurements (quantities with uncertainties).

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.group

Adds pint the capability to group units.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.system

Adds pint the capability to system of units.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.

pint.facets.context

Adds pint the capability to contexts: predefined conversions between incompatible dimensions.

copyright

2022 by Pint Authors, see AUTHORS for more details.

license

BSD, see LICENSE for more details.