Skip to main content
`Ctrl`+`K`

# Specific API

These are the classes, exceptions and functions that you will use if you need to dig deeper into Pint or develop Pint.

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

pint.compat.check_upcast_type(obj: type) → bool

  Check if the type object is an upcast type.

pint.compat.eq(lhs: Any, rhs: Any, check_all: bool) → bool | Iterable[bool]

  Comparison of scalars and arrays.

  Parameters:

    - lhs – left-hand side

    - rhs – right-hand side

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

  Returns:

    `bool` or array_like of `bool`

pint.compat.fully_qualified_name(t: type) → str

  Return the fully qualified name of a type.

pint.compat.is_duck_array(obj: type) → bool

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

pint.compat.is_duck_array_type(cls: type) → bool

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

pint.compat.is_upcast_type(other: type) → bool

  Check if the type object is an upcast type.

pint.compat.isnan(obj: Any, check_all: bool) → bool | Iterable[bool]

  Test for NaN or NaT.

  Parameters:

    - obj – scalar or vector

    - check_all – 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.missing_dependency(package: str, display_name: str | None = None) → Callable[[...], NoReturn]

  Return a helper function that raises an exception when used.

  It provides a way delay a missing dependency exception until it is used.

pint.compat.upcast_type_map: Mapping[str, type | None] = {'pandas.DataFrame': None, 'pandas.Series': None, 'pandas.core.frame.DataFrame': None, 'pandas.core.series.Series': None, 'pint_pandas.pint_array.PintArray': None, 'xarray.core.dataarray.DataArray': None, 'xarray.core.dataset.Dataset': None, 'xarray.core.variable.Variable': None}

  Map type name to the actual type (for upcast types).

pint.compat.upcast_type_names = ('pint_pandas.pint_array.PintArray', 'xarray.core.dataarray.DataArray', 'xarray.core.dataset.Dataset', 'xarray.core.variable.Variable', 'pandas.core.series.Series', 'pandas.core.frame.DataFrame', 'pandas.Series', 'pandas.DataFrame', 'xarray.core.dataarray.DataArray')

  List upcast type names

pint.compat.zero_or_nan(obj: Any, check_all: bool) → bool | Iterable[bool]

  Test if obj is zero, NaN, or NaT.

  Parameters:

    - obj – scalar or vector

    - check_all – 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

  Base class for value converters.

## pint.definitions

Kept for backwards compatibility

copyright:

  2022 by Pint Authors, see AUTHORS for more details.

license:

  BSD, see LICENSE for more details.

class pint.definitions.Definition

  This is kept for backwards compatibility

  classmethod from_string(input_string: str, non_int_type: type = <class 'float'>) → Definition

    Parse a string into a definition object.

    Parameters:

      - input_string – Single line string.

      - non_int_type – Numerical type used for non integer values.

    Raises:

      DefinitionSyntaxError – If a syntax error was found.

## 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.DefinitionError(name: str, definition_type: type, msg: str)

  Raised when a definition is not properly constructed.

exception pint.errors.DefinitionSyntaxError(msg: str)

  Raised when a textual definition has a syntax error.

exception pint.errors.DimensionalityError(units1: Any, units2: Any, dim1: str = '', dim2: str = '', extra_msg: str = '')

  Raised when trying to convert between incompatible units.

exception pint.errors.LogarithmicUnitCalculusError(units1: Any, units2: Any | None = None)

  Raised on inappropriate operations with logarithmic units.

exception pint.errors.OffsetUnitCalculusError(units1: Any, units2: Any | None = None)

  Raised on ambiguous operations with offset units.

exception pint.errors.PintError

  Base exception for all Pint errors.

exception pint.errors.PintTypeError

exception pint.errors.RedefinitionError(name: str, definition_type: type)

  Raised when a unit or prefix is redefined.

exception pint.errors.UndefinedBehavior(msg: str)

exception pint.errors.UndefinedUnitError(unit_names: str | Iterable[str])

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

exception pint.errors.UnexpectedScaleInContainer

exception pint.errors.UnitStrippedWarning(msg: str)

class pint.errors.WithDefErr

  Mixing class to make some classes more readable.

pint.errors.is_dim(name: str) → bool

  Return True if the name is flanked by square brackets [ and ].

pint.errors.is_valid_context_name(self, /)

  Return True if the string is a valid Python identifier, False otherwise.

  Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

pint.errors.is_valid_dimension_name(name: str) → bool

  Return True if the name is consistent with a dimension name.

  - flanked by square brackets.

  - empty dimension name or identifier.

pint.errors.is_valid_group_name(name: str) → bool

  Return False if the name contains a space in any position.

pint.errors.is_valid_prefix_alias(name: str) → bool

  Return False if the name contains a space in any position.

pint.errors.is_valid_prefix_name(name: str) → bool

  Return True if the name is a valid python identifier or empty.

pint.errors.is_valid_prefix_symbol(name: str) → bool

  Return False if the name contains a space in any position.

pint.errors.is_valid_system_name(self, /)

  Return True if the string is a valid Python identifier, False otherwise.

  Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

pint.errors.is_valid_unit_alias(name: str) → bool

  Return False if the name contains a space in any position.

pint.errors.is_valid_unit_name(self, /)

  Return True if the string is a valid Python identifier, False otherwise.

  Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

pint.errors.is_valid_unit_symbol(name: str) → bool

  Return False if the name contains a space in any position.

## 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: ~collections.abc.Iterable[tuple[str, ~numbers.Number]], as_ratio: bool = True, single_denominator: bool = False, product_fmt: str = ' * ', division_fmt: str = ' / ', power_fmt: str = '{} ** {}', parentheses_fmt: str = '({0})', exp_call: ~collections.abc.Callable[[~typing.Any], str] = <built-in method format of str object>, sort: bool = True) → str

  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})”)

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

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

  Returns:

    `str` – the formula as a string.

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

  Support default axis and tick labeling and default limits.

class pint.matplotlib.PintConverter(registry)

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

  static axisinfo(unit, axis)

    Return axis information for this particular unit.

  convert(value, unit, axis)

    Convert :Quantity instances for matplotlib to use.

  static default_units(x, axis)

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

pint.matplotlib.setup_matplotlib_handlers(registry, enable)

  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: EvalTreeNode | TokenInfo, operator: TokenInfo | None = None, right: EvalTreeNode | None = None)

  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: Callable[[Any], Any], bin_op: dict[str, Callable[[Any, Any], Any]] | None = None, un_op: dict[str, Callable[[Any], Any]] | None = None)

    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)

class pint.pint_eval.IteratorLookAhead(iter: Iterator[S])

  An iterator with lookahead buffer.

  Adapted: https://stackoverflow.com/a/1517965/1291237

  lookahead(n: int) → S

    Return an item n entries ahead in the iteration.

pint.pint_eval.build_eval_tree(tokens: Iterable[TokenInfo], op_priority: dict[str, int] | None = None) → EvalTreeNode

  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

  Raises:

    DefinitionSyntaxError – If there is a syntax error.

pint.pint_eval.plain_tokenizer(input_string: str) → Generator[TokenInfo, None, None]

  Standard python tokenizer

pint.pint_eval.tokenizer(input_string: str) → Generator[TokenInfo, None, None]

  Tokenizer capable of parsing uncertainties as v+/-u and v±u

pint.pint_eval.uncertainty_tokenizer(input_string: str) → Generator[TokenInfo, None, None]

  Tokenizer capable of parsing uncertainties as v+/-u and v±u

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

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

  get()

    Get the wrapped registry

  set(new_registry)

    Set the new registry

    Parameters:

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

    See also

    `set_application_registry`

class pint.registry.GenericUnitRegistry(*args: Any, **kwargs: Any)

class pint.registry.LazyRegistry(args=None, kwargs=None)

## 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: str | UnitsContainer | Unit | None) → 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:

    `callable()` – the wrapped function.

  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: str | Unit | Iterable[str | Unit | None] | None, args: str | Unit | Iterable[str | Unit | None] | None, strict: bool = True) → Callable[[Callable[..., Any]], Callable[..., Quantity]]

  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:

    `callable()` – the wrapper function.

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

Functions for testing whether pint quantities are equal.

copyright:

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

license:

  BSD, see LICENSE for more details.

pint.testing.assert_allclose(first, second, rtol: float = 1e-07, atol: float = 0, msg: str | None = None) → None

  Assert that two quantities are all close

  Unlike numpy, this uses a symmetric check of closeness.

  Parameters:

    - first – First quantity to compare

    - second – Second quantity to compare

    - rtol – Relative tolerance to use when checking for closeness.

    - atol – Absolute tolerance to use when checking for closeness.

    - msg – If supplied, message to show if the two quantities aren’t equal.

  Raises:

    AssertionError – The two quantities are not close to within the supplied tolerance.

pint.testing.assert_equal(first, second, msg: str | None = None) → None

  Assert that two quantities are equal

  Parameters:

    - first – First quantity to compare

    - second – Second quantity to compare

    - msg – If supplied, message to show if the two quantities aren’t equal.

  Raises:

    AssertionError – The two quantities are not equal.

## 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.ParserHelper(scale: complex | float | int | Decimal | Fraction = 1, *args, **kwargs)

  The ParserHelper stores in place the product of variables and their respective exponent and implements the corresponding operations. It also provides a scaling factor.

  For example:

    3 * m ** 2 becomes ParserHelper(3, m=2)

  Briefly is a UnitsContainer with a scaling factor.

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

  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.

  Parameters:

    - scale (`complex | float | int | decimal.Decimal | fractions.Fraction`) – Scaling factor. (default = 1)

    - **kwargs – Used to populate the dict of units and exponents.

  copy()

    Create a copy of this UnitsContainer.

  classmethod from_string(input_string: str, non_int_type: type = <class 'float'>) → ParserHelper

    Parse linear expression mathematical units and return a quantity object.

    Parameters:

      - input_string

      - non_int_type – Numerical type used for non integer values.

  classmethod from_word(input_word: str, non_int_type: type = <class 'float'>) → ParserHelper

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

    Equivalent to: ParserHelper(1, {input_word: 1})

    Parameters:

      - input_word

      - non_int_type – Numerical type used for non integer values.

class pint.util.PrettyIPython

  Mixin to add pretty-printers for IPython

class pint.util.SharedRegistryObject(*args, **kwargs)

  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.UnitsContainer(*args: Any, non_int_type: type | None = None, **kwargs: Any)

  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 new instances.

  Parameters:

    non_int_type – Numerical type used for non integer values.

  add(key: str, value: Number) → Self

    Create a new UnitsContainer adding value to the value existing for a given key.

    Parameters:

      - key – unit to which the value will be added.

      - value – value to be added.

    Returns:

      `UnitsContainer` – A copy of this container.

  copy() → Self

    Create a copy of this UnitsContainer.

  remove(keys: Iterable[str]) → Self

    Create a new UnitsContainer purged from given entries.

    Parameters:

      keys – Iterable of keys (units) to remove.

    Returns:

      `UnitsContainer` – A copy of this container.

  rename(oldkey: str, newkey: str) → Self

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

    Parameters:

      - oldkey – Existing key (unit).

      - newkey – New key (unit).

    Returns:

      `UnitsContainer` – A copy of this container.

pint.util.column_echelon_form(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[complex | float | int | ~decimal.Decimal | ~fractions.Fraction]], ntype: type = <class 'fractions.Fraction'>, transpose_result: bool = False) → tuple[list[list[complex | float | int | Decimal | Fraction]], list[list[complex | float | int | Decimal | Fraction]], list[int]]

  Calculate 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 = Fraction)

    - transpose_result – Indicates if the returned matrix should be transposed. (default = False)

  Returns:

    - `ech_matrix` – Column echelon form.

    - `id_matrix` – Transformed identity matrix.

    - `swapped` – Swapped rows.

pint.util.create_class_with_registry(registry: UnitRegistry, base_class: type[TT]) → type[TT]

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

pint.util.find_connected_nodes(graph: dict[TH, set[TH]], start: TH, visited: set[TH] | None = None) → set[TH] | None

  Find all nodes connected to a start node within a graph.

  Parameters:

    - graph – A graph given as a mapping of nodes to a set of all connected nodes to it.

    - start – Starting node.

    - visited – Mutable set to collect visited nodes. (default = None, empty set)

  Returns:

    `set[TH]` – The shortest path between two nodes.

pint.util.find_shortest_path(graph: dict[TH, set[TH]], start: TH, end: TH)

  Find shortest path between two nodes within a graph.

  Parameters:

    - graph – A graph given as a mapping of nodes to a set of all connected nodes to it.

    - start – Starting node.

    - end – End node.

  Returns:

    `list[TH]` – The shortest path between two nodes.

pint.util.getattr_maybe_raise(obj: Any, item: str)

  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 – attribute to be found.

  Raises:

    AttributeError –

pint.util.infer_base_unit(unit_like: QuantityOrUnitLike, registry: UnitRegistry | None = None) → UnitsContainer

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

  Parameters:

    - unit_like – Quantity or Unit to infer the plain units from.

    - registry – If provided, uses the registry’s UnitsContainer and parse_unit_name. If None, uses the registry attached to unit_like.

  Returns:

    `UnitsContainer`

  Raises:

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

pint.util.iterable(y: Any) → bool

  Check whether or not an object can be iterated over.

pint.util.matrix_apply(matrix: Iterable[Iterable[complex | float | int | Decimal | Fraction]], func: Callable[[complex | float | int | Decimal | Fraction], complex | float | int | Decimal | Fraction]) → list[list[complex | float | int | Decimal | Fraction]]

  Apply a function to individual elements within a matrix.

  Parameters:

    - matrix – A matrix given as an iterable of an iterable of numbers.

    - func – A callable that converts a number to another.

  Returns:

    `A new matrix in which each element has been replaced by new one.`

pint.util.matrix_to_string(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[complex | float | int | ~decimal.Decimal | ~fractions.Fraction]], row_headers: ~collections.abc.Iterable[str] | None = None, col_headers: ~collections.abc.Iterable[str] | None = None, fmtfun: ~collections.abc.Callable[[complex | float | int | ~decimal.Decimal | ~fractions.Fraction], str] = <built-in method format of str object>) → str

  Return a string representation of a matrix.

  Parameters:

    - matrix – A matrix given as an iterable of an iterable of numbers.

    - row_headers – An iterable of strings to serve as row headers. (default = None, meaning no row headers are printed.)

    - col_headers – An iterable of strings to serve as column headers. (default = None, meaning no col headers are printed.)

    - fmtfun – A callable to convert a number into string. (default = “{:0.0f}”.format)

  Returns:

    `str` – String representation of the matrix.

pint.util.pi_theorem(quantities: dict[str, Any], registry: UnitRegistry | None = None)

  Builds dimensionless quantities using the Buckingham π theorem

  Parameters:

    - quantities (`dict`) – mapping between variable name and units

    - registry – (default value = None)

  Returns:

    `type` – a list of dimensionless quantities expressed as dicts

pint.util.sized(y: Any) → bool

  Check whether or not an object has a defined length.

pint.util.solve_dependencies(dependencies: dict[TH, set[TH]]) → Generator[set[TH]]

  Solve a dependency graph.

  Parameters:

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

  Yields:

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

  Raises:

    ValueError – if a cyclic dependency is found.

pint.util.to_units_container(unit_like: QuantityOrUnitLike, registry: UnitRegistry | None = None) → UnitsContainer

  Convert a unit compatible type to a UnitsContainer.

  Parameters:

    - unit_like – Quantity or Unit to infer the plain units from.

    - registry – If provided, uses the registry’s UnitsContainer and parse_unit_name. If None, uses the registry attached to unit_like.

  Returns:

    `UnitsContainer`

pint.util.transpose(matrix: Iterable[Iterable[complex | float | int | Decimal | Fraction]]) → list[list[complex | float | int | Decimal | Fraction]]

  Return the transposed version of a matrix.

  Parameters:

    matrix – A matrix given as an iterable of an iterable of numbers.

  Returns:

    `Matrix` – The transposed version of the matrix.

class pint.util.udict

  Custom dict implementing __missing__.

  copy() → Self

    Return a shallow copy of the dict.