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) bool | 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) bool | 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: str | None = 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.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] [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'>) 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: Any | None = None)[source]#
Raised on inappropriate operations with logarithmic units.
- exception pint.errors.OffsetUnitCalculusError(units1: Any, units2: Any | None = 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: str | Iterable[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.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: ~typing.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 [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})”)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)[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: EvalTreeNode | TokenInfo, operator: TokenInfo | None = None, right: EvalTreeNode | None = 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: dict[str, Callable[[Any, Any], Any]] | None = None, un_op: dict[str, Callable[[Any], Any]] | None = 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: Iterable[TokenInfo], op_priority: dict[str, int] | None = None) 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: 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: str | Unit | Iterable[str | Unit | None] | None, args: str | Unit | Iterable[str | Unit | None] | None, 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: float | int | Decimal | 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) 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 (
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'>) 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'>) 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: type | None = 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) return new instances.
- Parameters:
non_int_type – Numerical type used for non integer values.
- add(key: str, value: Number) 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.
- pint.util.column_echelon_form(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[float | int | ~decimal.Decimal | ~fractions.Fraction]], ntype: type = <class 'fractions.Fraction'>, transpose_result: bool = False) tuple[list[list[float | int | Decimal | Fraction]], list[list[float | int | Decimal | 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: TH, visited: set[TH] | None = None) set[TH] | None [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: TH, end: TH, path: list[TH] | None = 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: UnitRegistry | None = 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: Iterable[Iterable[float | int | Decimal | Fraction]], func: Callable[[float | int | Decimal | Fraction], float | int | Decimal | Fraction]) list[list[float | int | Decimal | 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[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[[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: UnitRegistry | None = None)[source]#
Builds dimensionless quantities using the Buckingham π theorem
- pint.util.solve_dependencies(dependencies: dict[TH, set[TH]]) 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: UnitRegistry | None = 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: Iterable[Iterable[float | int | Decimal | Fraction]]) list[list[float | int | Decimal | 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.