Specific API
Contents
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.
- pint.compat.eq(lhs: Any, rhs: Any, check_all: bool) Union[bool, collections.abc.Iterable[bool]] [source]#
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 ofbool
- pint.compat.is_duck_array(obj: type) bool [source]#
Check if an object represents a (non-Quantity) duck array type.
- pint.compat.is_duck_array_type(cls: type) bool [source]#
Check if the type object represents a (non-Quantity) duck array type.
- pint.compat.isnan(obj: Any, check_all: bool) Union[bool, collections.abc.Iterable[bool]] [source]#
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 ofbool.
– Always return False for non-numeric types.
- pint.compat.missing_dependency(package: str, display_name: Optional[str] = None) Callable[[...], NoReturn] [source]#
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.tokenizer(input_string: str) collections.abc.Generator[tokenize.TokenInfo, None, None] [source]#
Tokenize an input string, encoded as UTF-8 and skipping the ENCODING token.
See also
- pint.compat.upcast_type_map: collections.abc.Mapping[str, Optional[type]] = {'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', 'xarray.core.dataarray.DataArray')#
List upcast type names
- pint.compat.zero_or_nan(obj: Any, check_all: bool) Union[bool, collections.abc.Iterable[bool]] [source]#
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 ofbool.
– 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.
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
- classmethod from_string(input_string: str, non_int_type: type = <class 'float'>) pint.definitions.Definition [source]#
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)[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.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.
- pint.errors.is_dim(name: str) bool [source]#
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 [source]#
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 [source]#
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.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: typing.Callable[[typing.Any], str] = <built-in method format of str object>, locale: typing.Optional[str] = None, babel_length: str = 'long', babel_plural_form: str = 'one', sort: bool = True) str [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.latex_escape(string: str) str [source]#
Prepend characters that have a special meaning in LaTeX with a backslash.
- pint.formatting.register_unit_format(name: str)[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.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.
- 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: Union[pint.pint_eval.EvalTreeNode, tokenize.TokenInfo], operator: Optional[tokenize.TokenInfo] = None, right: Optional[pint.pint_eval.EvalTreeNode] = 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: Callable[[Any], Any], bin_op: Optional[dict[str, Callable[[Any, Any], Any]]] = None, un_op: Optional[dict[str, Callable[[Any], Any]]] = None)[source]#
Evaluate node.
- Parameters
define_op (
callable()
) – Translates tokens into objects.bin_op (
dict
orNone
, optional) – (Default value = _BINARY_OPERATOR_MAP)un_op (
dict
orNone
, optional) – (Default value = _UNARY_OPERATOR_MAP)
- pint.pint_eval.build_eval_tree(tokens: collections.abc.Iterable[tokenize.TokenInfo], op_priority: Optional[dict[str, int]] = None) pint.pint_eval.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
- Raises
DefinitionSyntaxError – If there is a syntax error.
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.
- set(new_registry)[source]#
Set the new registry
- Parameters
new_registry (
ApplicationRegistry
orLazyRegistry
orUnitRegistry
) – 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: 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
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: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], args: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], strict: bool = True) Callable[[Callable[..., Any]], Callable[..., Quantity]] [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 ofstr
orpint.Unit
) – Units of each of the return values. Use None to skip argument conversion.args (
str
,pint.Unit
, or iterable ofstr
orpint.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.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: Union[float, int, decimal.Decimal, fractions.Fraction] = 1, *args, **kwargs)[source]#
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)
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 (
Union[float
,int
,decimal.Decimal
,fractions.Fraction]
) – Scaling factor. (default = 1)**kwargs – Used to populate the dict of units and exponents.
- classmethod from_string(input_string: str, non_int_type: type = <class 'float'>) pint.util.ParserHelper [source]#
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'>) pint.util.ParserHelper [source]#
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.
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: Optional[type] = None, **kwargs: Any)[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)
- Parameters
non_int_type – Numerical type used for non integer values.
- add(key: str, value: numbers.Number) typing_extensions.Self [source]#
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.
- remove(keys: collections.abc.Iterable[str]) typing_extensions.Self [source]#
Create a new UnitsContainer purged from given entries.
- Parameters
keys – Iterable of keys (units) to remove.
- Returns
UnitsContainer
– A copy of this container.
- pint.util.column_echelon_form(matrix: collections.abc.Iterable[collections.abc.Iterable[typing.Union[float, int, decimal.Decimal, fractions.Fraction]]], ntype: type = <class 'fractions.Fraction'>, transpose_result: bool = False) tuple[list[list[Union[float, int, decimal.Decimal, fractions.Fraction]]], list[list[Union[float, int, decimal.Decimal, fractions.Fraction]]], list[int]] [source]#
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] [source]#
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: pint.util.TH, visited: Optional[set[TH]] = None) Optional[set[TH]] [source]#
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: pint.util.TH, end: pint.util.TH, path: Optional[list[TH]] = None)[source]#
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.
path – Path to prepend to the one found. (default = None, empty path.)
- Returns
list[TH]
– The shortest path between two nodes.
- pint.util.getattr_maybe_raise(obj: Any, item: str)[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 – attribute to be found.
- Raises
- pint.util.infer_base_unit(unit_like: QuantityOrUnitLike, registry: Optional[UnitRegistry] = None) UnitsContainer [source]#
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.matrix_apply(matrix: collections.abc.Iterable[collections.abc.Iterable[Union[float, int, decimal.Decimal, fractions.Fraction]]], func: Callable[[Union[float, int, decimal.Decimal, fractions.Fraction]], Union[float, int, decimal.Decimal, fractions.Fraction]]) list[list[Union[float, int, decimal.Decimal, fractions.Fraction]]] [source]#
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[typing.Union[float, int, decimal.Decimal, fractions.Fraction]]], row_headers: typing.Optional[collections.abc.Iterable[str]] = None, col_headers: typing.Optional[collections.abc.Iterable[str]] = None, fmtfun: typing.Callable[[typing.Union[float, int, decimal.Decimal, fractions.Fraction]], str] = <built-in method format of str object>) str [source]#
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: Optional[UnitRegistry] = None)[source]#
Builds dimensionless quantities using the Buckingham π theorem
- pint.util.solve_dependencies(dependencies: dict[TH, set[TH]]) collections.abc.Generator[set[TH], None, None] [source]#
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: Optional[UnitRegistry] = None) UnitsContainer [source]#
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: collections.abc.Iterable[collections.abc.Iterable[Union[float, int, decimal.Decimal, fractions.Fraction]]]) list[list[Union[float, int, decimal.Decimal, fractions.Fraction]]] [source]#
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.