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

Returns

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)

Returns

bool

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

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

Parameters

other (object)

Returns

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#

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[source]#

This is kept for backwards compatibility

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)[source]#

Raised when a definition is not properly constructed.

exception pint.errors.DefinitionSyntaxError(msg: str)[source]#

Raised when a textual definition has a syntax error.

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

Raised when trying to convert between incompatible units.

exception pint.errors.LogarithmicUnitCalculusError(units1: Any, units2: Optional[Any] = None)[source]#

Raised on inappropriate operations with logarithmic units.

exception pint.errors.OffsetUnitCalculusError(units1: Any, units2: Optional[Any] = None)[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: str, definition_type: Type)[source]#

Raised when a unit or prefix is redefined.

exception pint.errors.UndefinedUnitError(unit_names: Union[str, Tuple[str, ...]])[source]#

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

exception pint.errors.UnexpectedScaleInContainer[source]#
exception pint.errors.UnitStrippedWarning(msg: 'str')[source]#
class pint.errors.WithDefErr[source]#

Mixing class to make some classes more readable.

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

str – the formula as a string.

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

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: Union[str, UnitsContainer, 'Unit', None]) 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

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: 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
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.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=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

type – 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.

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

Returns

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

type – column echelon form, transformed identity matrix, swapped rows

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.

Returns

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

type – a list of dimensionless quantities expressed as dicts

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

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

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