API reference#

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

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

pi_theorem(quantities)[source]#

Builds dimensionless quantities using the Buckingham π theorem

Parameters

quantities (dict) – mapping between variable name and units

Returns

list – a list of dimensionless quantities expressed as dicts

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

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

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.

class pint.facets.plain.AliasDefinition(name: str, aliases: Tuple[str, ...])[source]#

Additional alias(es) for an already existing unit.

aliases: Tuple[str, ...]#

aditional names for the same unit

name: str#

name of the already existing unit

class pint.facets.plain.DefaultsDefinition(group: Optional[str], system: Optional[str])[source]#

Directive to store default values.

class pint.facets.plain.DimensionDefinition(name: str)[source]#

Definition of a root dimension

name: str#

name of the dimension

class pint.facets.plain.PlainQuantity(value: str, units: Optional[Union[str, UnitsContainer, Unit]] = None)[source]#
class pint.facets.plain.PlainQuantity(value: Sequence, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class pint.facets.plain.PlainQuantity(value: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class pint.facets.plain.PlainQuantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)

Implements a class to describe a physical quantity: the product of a numerical value and a unit of measurement.

Parameters
  • value (str, pint.PlainQuantity or any numeric type) – Value of the physical quantity to be created.

  • units (UnitsContainer, str or pint.PlainQuantity) – Units of the physical quantity to be created.

check(dimension: Union[str, UnitsContainer, Unit]) bool[source]#

Return true if the quantity’s dimension matches passed dimension.

default_format: str = ''#

Default formatting string.

property dimensionality: UnitsContainerT#
Returns

dict – Dimensionality of the PlainQuantity, e.g. {length: 1, time: -1}

classmethod from_list(quant_list: List[pint.facets.plain.quantity.PlainQuantity], units=None) pint.facets.plain.quantity.PlainQuantity[numpy.ndarray][source]#

Transforms a list of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used. Same as from_sequence.

If units is not specified and list is empty, the unit cannot be determined and a ValueError is raised.

Parameters
  • quant_list (list of pint.PlainQuantity) – list of pint.PlainQuantity

  • units (UnitsContainer, str or pint.PlainQuantity) – units of the physical quantity to be created (Default value = None)

Returns

pint.PlainQuantity

classmethod from_sequence(seq: Sequence[pint.facets.plain.quantity.PlainQuantity], units=None) pint.facets.plain.quantity.PlainQuantity[numpy.ndarray][source]#

Transforms a sequence of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used.

If units is not specified and sequence is empty, the unit cannot be determined and a ValueError is raised.

Parameters
  • seq (sequence of pint.PlainQuantity) – sequence of pint.PlainQuantity

  • units (UnitsContainer, str or pint.PlainQuantity) – units of the physical quantity to be created (Default value = None)

Returns

pint.PlainQuantity

is_compatible_with(other: Any, *contexts: Union[str, Context], **ctx_kwargs: Any) bool[source]#

check if the other object is compatible

Parameters
  • other – The object to check. Treated as dimensionless if not a PlainQuantity, Unit or str.

  • *contexts (str or pint.Context) – Contexts to use in the transformation.

  • **ctx_kwargs – Values for the Context/s

Returns

bool

ito(other=None, *contexts, **ctx_kwargs) None[source]#

Inplace rescale to different units.

Parameters
  • other (pint.PlainQuantity, str or dict) – Destination units. (Default value = None)

  • *contexts (str or pint.Context) – Contexts to use in the transformation.

  • **ctx_kwargs – Values for the Context/s

ito_base_units() None[source]#

Return PlainQuantity rescaled to plain units.

ito_reduced_units() None[source]#

Return PlainQuantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (e.g., ‘J/kg’ will not be reduced to m**2/s**2), nor can it make use of contexts at this time.

ito_root_units() None[source]#

Return PlainQuantity rescaled to root units.

property m: pint._typing._MagnitudeType#

PlainQuantity’s magnitude. Short form for magnitude

m_as(units) pint._typing._MagnitudeType[source]#

PlainQuantity’s magnitude expressed in particular units.

Parameters

units (pint.PlainQuantity, str or dict) – destination units

property magnitude: pint._typing._MagnitudeType#

PlainQuantity’s magnitude. Long form for m

to(other=None, *contexts, **ctx_kwargs) pint.facets.plain.quantity.PlainQuantity[pint._typing._MagnitudeType][source]#

Return PlainQuantity rescaled to different units.

Parameters
  • other (pint.PlainQuantity, str or dict) – destination units. (Default value = None)

  • *contexts (str or pint.Context) – Contexts to use in the transformation.

  • **ctx_kwargs – Values for the Context/s

Returns

pint.PlainQuantity

to_base_units() pint.facets.plain.quantity.PlainQuantity[pint._typing._MagnitudeType][source]#

Return PlainQuantity rescaled to plain units.

to_compact(unit=None) pint.facets.plain.quantity.PlainQuantity[pint._typing._MagnitudeType][source]#

“Return PlainQuantity rescaled to compact, human-readable units.

To get output in terms of a different unit, use the unit parameter.

Examples

>>> import pint
>>> ureg = pint.UnitRegistry()
>>> (200e-9*ureg.s).to_compact()
<Quantity(200.0, 'nanosecond')>
>>> (1e-2*ureg('kg m/s^2')).to_compact('N')
<Quantity(10.0, 'millinewton')>
to_reduced_units() pint.facets.plain.quantity.PlainQuantity[pint._typing._MagnitudeType][source]#

Return PlainQuantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (intentionally), nor can it make use of contexts at this time.

to_root_units() pint.facets.plain.quantity.PlainQuantity[pint._typing._MagnitudeType][source]#

Return PlainQuantity rescaled to root units.

property u: Unit#

PlainQuantity’s units. Short form for units

property units: Unit#

PlainQuantity’s units. Long form for u

class pint.facets.plain.PlainRegistry(*args, **kwargs)[source]#

Base class for all registries.

Capabilities:

  • Register units, prefixes, and dimensions, and their relations.

  • Convert between units.

  • Find dimensionality of a unit.

  • Parse units with prefix and/or suffix.

  • Parse expressions.

  • Parse a definition file.

  • Allow extending the definition file parser by registering @ directives.

Parameters
  • filename (str or None) – 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.

  • 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

  • non_int_type (type) – numerical type used for non integer values. (Default: float)

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

  • separate_format_defaults (bool, optional) – Separate the default format into magnitude and unit formats as soon as possible. The deprecated default is not to separate. This will change in a future release.

auto_reduce_dimensions#

Determines if dimensionality should be reduced on appropriate operations.

case_sensitive#

Default unit case sensitivity

convert(value: pint.facets.plain.registry.T, src: Union[Quantity, str, UnitsContainer, Unit], dst: Union[Quantity, str, UnitsContainer, Unit], inplace: bool = False) pint.facets.plain.registry.T[source]#

Convert value from some source to destination units.

Parameters
  • value – value

  • src (pint.Quantity or str) – source units.

  • dst (pint.Quantity or str) – destination units.

  • inplace – (Default value = False)

Returns

type – converted value

property default_format: str#

Default formatting string for quantities.

define(definition)[source]#

Add unit to the registry.

Parameters

definition (str or Definition) – a dimension, unit or prefix definition.

fmt_locale: Optional[Locale] = None#

Babel.Locale instance or None

get_base_units(input_units, check_nonmult=True, system=None)[source]#

Convert unit or dict of units to the plain units.

If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.

Parameters
  • input_units (UnitsContainer or str) – units

  • check_nonmult (bool) – If True, None will be returned as the multiplicative factor if non-multiplicative units are found in the final Units. (Default value = True)

  • system – (Default value = None)

Returns

Number, pint.Unit – multiplicative factor, plain units

get_dimensionality(input_units) pint.util.UnitsContainer[source]#

Convert unit or dict of units or dimensions to a dict of plain dimensions dimensions

get_name(name_or_alias: str, case_sensitive: Optional[bool] = None) str[source]#

Return the canonical name of a unit.

get_root_units(input_units: Union[str, UnitsContainer, Unit], check_nonmult: bool = True) Tuple[numbers.Number, pint.facets.plain.unit.PlainUnit][source]#

Convert unit or dict of units to the root units.

If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.

Parameters
  • input_units (UnitsContainer or str) – units

  • check_nonmult (bool) – if True, None will be returned as the multiplicative factor if a non-multiplicative units is found in the final Units. (Default value = True)

Returns

Number, pint.Unit – multiplicative factor, plain units

get_symbol(name_or_alias: str, case_sensitive: Optional[bool] = None) str[source]#

Return the preferred alias for a unit.

is_compatible_with(obj1: Any, obj2: Any, *contexts: Union[str, Context], **ctx_kwargs) bool[source]#

check if the other object is compatible

Parameters
  • obj1, obj2 – The objects to check against each other. Treated as dimensionless if not a Quantity, Unit or str.

  • *contexts (str or pint.Context) – Contexts to use in the transformation.

  • **ctx_kwargs – Values for the Context/s

Returns

bool

load_definitions(file, is_resource: bool = False)[source]#

Add units and prefixes defined in a definition text file.

Parameters
  • file – can be a filename or a line iterable.

  • is_resource – used to indicate that the file is a resource file and therefore should be loaded from the package. (Default value = False)

parse_expression(input_string: str, case_sensitive: Optional[bool] = None, use_decimal: bool = False, **values) Quantity[source]#

Parse a mathematical expression including units and return a quantity object.

Numerical constants can be specified as keyword arguments and will take precedence over the names defined in the registry.

Parameters
  • input_string

  • case_sensitive – (Default value = None, which uses registry setting)

  • use_decimal – (Default value = False)

  • **values

parse_pattern(input_string: str, pattern: str, case_sensitive: Optional[bool] = None, use_decimal: bool = False, many: bool = False) Optional[Union[List[str], str]][source]#

Parse a string with a given regex pattern and returns result.

Parameters
  • input_string

  • pattern_string – The regex parse string

  • case_sensitive – (Default value = None, which uses registry setting)

  • use_decimal – (Default value = False)

  • many – Match many results (Default value = False)

parse_unit_name(unit_name: str, case_sensitive: Optional[bool] = None) Tuple[Tuple[str, str, str], ...][source]#

Parse a unit to identify prefix, unit name and suffix by walking the list of prefix and suffix. In case of equivalent combinations (e.g. (‘kilo’, ‘gram’, ‘’) and (‘’, ‘kilogram’, ‘’), prefer those with prefix.

Parameters
  • unit_name

  • case_sensitive (bool or None) – Control if unit lookup is case sensitive. Defaults to None, which uses the registry’s case_sensitive setting

Returns

tuple of tuples (str, str, str) – all non-equivalent combinations of (prefix, unit name, suffix)

parse_units(input_string: str, as_delta: Optional[bool] = None, case_sensitive: Optional[bool] = None) Unit[source]#

Parse a units expression and returns a UnitContainer with the canonical names.

The expression can only contain products, ratios and powers of units.

Parameters
  • input_string (str)

  • as_delta (bool or None) – if the expression has multiple units, the parser will interpret non multiplicative units as their delta_ counterparts. (Default value = None)

  • case_sensitive (bool or None) – Control if unit parsing is case sensitive. Defaults to None, which uses the registry’s setting.

Returns

pint.Unit

separate_format_defaults#

mode used to fill in the format defaults

set_fmt_locale(loc: Optional[str]) None[source]#

Change the locale used by default by format_babel.

Parameters

loc (str or None) – None` (do not translate), ‘sys’ (detect the system locale) or a locale id string.

class pint.facets.plain.PlainUnit(*args, **kwargs)[source]#

Implements a class to describe a unit supporting math operations.

default_format: str = ''#

Default formatting string.

property dimensionality: UnitsContainer#
Returns

dict – Dimensionality of the PlainUnit, e.g. {length: 1, time: -1}

property dimensionless: bool#

Return True if the PlainUnit is dimensionless; False otherwise.

from_(value, strict=True, name='value')[source]#

Converts a numerical value or quantity to this unit

Parameters
  • value – a Quantity (or numerical value if strict=False) to convert

  • strict – boolean to indicate that only quantities are accepted (Default value = True)

  • name – descriptive name to use if an exception occurs (Default value = “value”)

Returns

type – The converted value as this unit

is_compatible_with(other: Any, *contexts: Union[str, Context], **ctx_kwargs: Any) bool[source]#

check if the other object is compatible

Parameters
  • other – The object to check. Treated as dimensionless if not a Quantity, PlainUnit or str.

  • *contexts (str or pint.Context) – Contexts to use in the transformation.

  • **ctx_kwargs – Values for the Context/s

Returns

bool

m_from(value, strict=True, name='value')[source]#

Converts a numerical value or quantity to this unit, then returns the magnitude of the converted value

Parameters
  • value – a Quantity (or numerical value if strict=False) to convert

  • strict – boolean to indicate that only quantities are accepted (Default value = True)

  • name – descriptive name to use if an exception occurs (Default value = “value”)

Returns

type – The magnitude of the converted value

class pint.facets.plain.PrefixDefinition(name: str, value: numbers.Number, defined_symbol: Optional[str] = '', aliases: Tuple[str, ...] = ())[source]#

Definition of a prefix.

aliases: Tuple[str, ...] = ()#

additional names for the same prefix

defined_symbol: Optional[str] = ''#

canonical symbol

name: str#

name of the prefix

value: numbers.Number#

scaling value for this prefix

class pint.facets.plain.ScaleConverter(scale: float)[source]#

A linear transformation without offset.

class pint.facets.plain.UnitDefinition(name: str, defined_symbol: ty.Optional[str], aliases: ty.Tuple[str, ...], converter: ty.Optional[ty.Union[Callable, Converter]], reference: ty.Optional[UnitsContainer])[source]#

Definition of a unit.

aliases: Tuple[str, ...]#

additional names for the same unit

converter: Optional[Union[Callable, pint.converters.Converter]]#

A functiont that converts a value in these units into the reference units

defined_symbol: Optional[str]#

canonical symbol

property is_base: bool#

Indicates if it is a base unit.

name: str#

canonical name of the unit

reference: Optional[UnitsContainer]#

Reference units.

class pint.facets.plain.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.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.

class pint.facets.nonmultiplicative.NonMultiplicativeRegistry(*args, **kwargs)[source]#

Handle of non multiplicative units (e.g. Temperature).

Capabilities: - Register non-multiplicative units and their relations. - Convert between non-multiplicative units.

Parameters
  • default_as_delta (bool) – If True, non-multiplicative units are interpreted as their delta counterparts in multiplications.

  • autoconvert_offset_to_baseunit (bool) – If True, non-multiplicative units are converted to plain units in multiplications.

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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#
default_as_delta#

When performing a multiplication of units, interpret non-multiplicative units as their delta counterparts.

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.

class pint.facets.formatting.FormattingRegistry(*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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#

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.

class pint.facets.numpy.NumpyRegistry(*args, **kwargs)[source]#
class Unit(*args, **kwargs)#

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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.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.

class pint.facets.measurement.Measurement(value, error, units=<object object>)[source]#

Implements a class to describe a quantity with uncertainty.

Parameters
  • value (pint.Quantity or any numeric type) – The expected value of the measurement

  • error (pint.Quantity or any numeric type) – The error or uncertainty of the measurement

class pint.facets.measurement.MeasurementRegistry(*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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#

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.

class pint.facets.group.Group(*args, **kwargs)[source]#

A group is a set of units.

Units can be added directly or by including other groups.

Members are computed dynamically, that is if a unit is added to a group X all groups that include X are affected.

The group belongs to one Registry.

See GroupDefinition for the definition file syntax.

add_groups(*group_names)[source]#

Add groups to group.

add_units(*unit_names)[source]#

Add units to group.

classmethod from_lines(lines, define_func, non_int_type=<class 'float'>) pint.facets.group.objects.Group[source]#

Return a Group object parsing an iterable of lines.

Parameters
  • lines (list[str]) – iterable

  • define_func (callable()) – Function to define a unit in the registry; it must accept a single string as a parameter.

invalidate_members()[source]#

Invalidate computed members in this Group and all parent nodes.

property members#

Names of the units that are members of the group.

Calculated to include to all units in all included _used_groups.

name#

str

Type

type

remove_groups(*group_names)[source]#

Remove groups from group.

remove_units(*unit_names)[source]#

Remove units from group.

class pint.facets.group.GroupDefinition(name: str, using_group_names: Tuple[str, ...], definitions: Tuple[pint.facets.plain.definitions.UnitDefinition, ...])[source]#

Definition of a group.

definitions: Tuple[pint.facets.plain.definitions.UnitDefinition, ...]#

definitions for the units existing within the group

name: str#

name of the group

using_group_names: Tuple[str, ...]#

unit groups that will be included within the group

class pint.facets.group.GroupRegistry(*args, **kwargs)[source]#

Handle of Groups.

Group units

Capabilities: - Register groups. - Parse @group directive.

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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#
get_group(name: str, create_if_needed: bool = True) pint.facets.group.objects.Group[source]#

Return a Group.

Parameters
  • name (str) – Name of the group to be

  • create_if_needed (bool) – If True, create a group if not found. If False, raise an Exception. (Default value = True)

Returns

Group – Group

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.

class pint.facets.system.System(*args, **kwargs)[source]#

A system is a Group plus a set of plain units.

Members are computed dynamically, that is if a unit is added to a group X all groups that include X are affected.

The System belongs to one Registry.

See SystemDefinition for the definition file syntax.

add_groups(*group_names)[source]#

Add groups to group.

base_units#

Maps root unit names to a dict indicating the new unit and its exponent. :type: dict[str, dict[str, number]]]

derived_units#

Derived unit names. :type: set(str)

format_babel(locale)[source]#

translate the name of the system.

invalidate_members()[source]#

Invalidate computed members in this Group and all parent nodes.

name#

Name of the system :type: str

remove_groups(*group_names)[source]#

Remove groups from group.

class pint.facets.system.SystemDefinition(name: str, using_group_names: Tuple[str, ...], rules: Tuple[pint.facets.system.definitions.BaseUnitRule, ...])[source]#

Definition of a System.

name: str#

name of the system

rules: Tuple[pint.facets.system.definitions.BaseUnitRule, ...]#

rules to define new base unit within the system.

using_group_names: Tuple[str, ...]#

unit groups that will be included within the system

class pint.facets.system.SystemRegistry(*args, **kwargs)[source]#

Handle of Systems.

Conversion between units with different dimensions according to previously established relations (contexts). (e.g. in the spectroscopy, conversion between frequency and energy is possible)

Capabilities:

  • Register systems.

  • List systems

  • Get or get the default system.

  • Parse @group directive.

class Group(*args, **kwargs)#
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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#
get_base_units(input_units: Union[UnitLike, Quantity], check_nonmult: bool = True, system: Union[str, System, None] = None) Tuple[Number, Unit][source]#

Convert unit or dict of units to the plain units.

If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.

Unlike PlainRegistry, in this registry root_units might be different from base_units

Parameters
  • input_units (UnitsContainer or str) – units

  • check_nonmult (bool) – if True, None will be returned as the multiplicative factor if a non-multiplicative units is found in the final Units. (Default value = True)

  • system – (Default value = None)

Returns

type – multiplicative factor, plain units

get_system(name: str, create_if_needed: bool = True) pint.facets.system.objects.System[source]#

Return a Group.

Parameters
  • name (str) – Name of the group to be

  • create_if_needed (bool) – If True, create a group if not found. If False, raise an Exception. (Default value = True)

Returns

type – System

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.

class pint.facets.context.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: pint.facets.context.objects.Context, **defaults) pint.facets.context.objects.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

Returns

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

Returns

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.

class pint.facets.context.ContextDefinition(name: str, aliases: Tuple[str, ...], defaults: Dict[str, numbers.Number], relations: Tuple[pint.facets.context.definitions.Relation, ...], redefinitions: Tuple[pint.facets.plain.definitions.UnitDefinition, ...])[source]#

Definition of a Context

aliases: Tuple[str, ...]#

other na

name: str#

name of the context

property variables: Set[str, ...]#

Return all variable names in all transformations.

class pint.facets.context.ContextRegistry(*args, **kwargs)[source]#

Handle of Contexts.

Conversion between units with different dimensions according to previously established relations (contexts). (e.g. in the spectroscopy, conversion between frequency and energy is possible)

Capabilities:

  • Register contexts.

  • Enable and disable contexts.

  • Parse @context directive.

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

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#

Add a transformation function to the context.

defaults#

Maps defaults variable names to values

classmethod from_context(context: pint.facets.context.objects.Context, **defaults) pint.facets.context.objects.Context#

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

Returns

pint.Context

funcs#

Maps (src, dst) -> transformation function

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

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

Returns

tuple

redefine(definition: str) None#

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#

Add a transformation function to the context.

transform(src, dst, registry, value)#

Transform a value.

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: pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.Magnitude], units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Quantity(value: pint.facets.plain.quantity.Magnitude, units: Optional[Union[str, UnitsContainer, Unit]] = None)
class Unit(*args, **kwargs)#
add_context(context: Union[pint.facets.context.objects.Context, pint.facets.context.definitions.ContextDefinition]) None[source]#

Add a context object to the registry.

The context will be accessible by its name and aliases.

Notice that this method will NOT enable the context; see enable_contexts().

context(*names, **kwargs) AbstractContextManager[pint.facets.context.objects.Context][source]#

Used as a context manager, this function enables to activate a context which is removed after usage.

Parameters
  • *names (name(s) of the context(s).)

  • **kwargs (keyword arguments for the contexts.)

Examples

Context can be called by their name:

>>> import pint.facets.context.objects
>>> import pint
>>> ureg = pint.UnitRegistry()
>>> ureg.add_context(pint.facets.context.objects.Context('one'))
>>> ureg.add_context(pint.facets.context.objects.Context('two'))
>>> with ureg.context('one'):
...     pass

If a context has an argument, you can specify its value as a keyword argument:

>>> with ureg.context('one', n=1):
...     pass

Multiple contexts can be entered in single call:

>>> with ureg.context('one', 'two', n=1):
...     pass

Or nested allowing you to give different values to the same keyword argument:

>>> with ureg.context('one', n=1):
...     with ureg.context('two', n=2):
...         pass

A nested context inherits the defaults from the containing context:

>>> with ureg.context('one', n=1):
...     # Here n takes the value of the outer context
...     with ureg.context('two'):
...         pass
disable_contexts(n: Optional[int] = None) None[source]#

Disable the last n enabled contexts.

Parameters

n (int) – Number of contexts to disable. Default: disable all contexts.

enable_contexts(*names_or_contexts: Union[str, pint.facets.context.objects.Context], **kwargs) None[source]#

Enable contexts provided by name or by object.

Parameters
  • *names_or_contexts – one or more contexts or context names/aliases

  • **kwargs – keyword arguments for the context(s)

Examples

See context()

remove_context(name_or_alias: str) pint.facets.context.objects.Context[source]#

Remove a context from the registry and return it.

Notice that this methods will not disable the context; see disable_contexts().

with_context(name, **kwargs) Callable[[pint._typing.F], pint._typing.F][source]#

Decorator to wrap a function call in a Pint context.

Use it to ensure that a certain context is active when calling a function.

Parameters
  • name – name of the context.

  • **kwargs – keyword arguments for the context

Returns

callable (the wrapped function.)

Examples

>>> @ureg.with_context('sp')
... def my_cool_fun(wavelength):
...     print('This wavelength is equivalent to: %s', wavelength.to('terahertz'))