Developer reference

All Modules

pint

Pint is Python module/package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units.

copyright:

2016 by Pint Authors, see AUTHORS for more details.

license:

BSD, see LICENSE for more details.

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

Return type:

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

Return type:

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.

exception pint.DefinitionSyntaxError(msg, *, filename=None, lineno=None)[source]

Raised when a textual definition has a syntax error.

exception pint.DimensionalityError(units1, units2, dim1='', dim2='', *, extra_msg='')[source]

Raised when trying to convert between incompatible units.

exception pint.LogarithmicUnitCalculusError[source]

Raised on inappropriate operations with logarithmic units.

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

exception pint.OffsetUnitCalculusError[source]

Raised on ambiguous operations with offset units.

exception pint.PintError[source]

Base exception for all Pint errors.

class pint.Quantity(value: str, units: Optional[UnitLike] = None)[source]
class pint.Quantity(value: Sequence, units: Optional[UnitLike] = None)
class pint.Quantity(value: Quantity[Magnitude], units: Optional[UnitLike] = None)
class pint.Quantity(value: Magnitude, units: Optional[UnitLike] = None)

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

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

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

check(dimension: UnitLike) bool[source]

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

compute(**kwargs)[source]

Compute the Dask array wrapped by pint.Quantity.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.compute.

Returns:

A pint.Quantity wrapped numpy array.

Return type:

pint.Quantity

default_format: str = ''

Default formatting string.

property dimensionality: UnitsContainerT

returns: Dimensionality of the Quantity, e.g. {length: 1, time: -1} :rtype: dict

dot(b)[source]

Dot product of two arrays.

Wraps np.dot().

classmethod from_list(quant_list: List[Quantity], units=None) Quantity[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.Quantity) – list of pint.Quantity

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

Return type:

pint.Quantity

classmethod from_sequence(seq: Sequence[Quantity], units=None) Quantity[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.Quantity) – sequence of pint.Quantity

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

Return type:

pint.Quantity

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, Unit or str.

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

  • **ctx_kwargs – Values for the Context/s

Return type:

bool

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

Inplace rescale to different units.

Parameters:
  • other (pint.Quantity, 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 Quantity rescaled to base units.

ito_reduced_units() None[source]

Return Quantity 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 Quantity rescaled to root units.

property m: _MagnitudeType

Quantity’s magnitude. Short form for magnitude

m_as(units) _MagnitudeType[source]

Quantity’s magnitude expressed in particular units.

Parameters:

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

property magnitude: _MagnitudeType

Quantity’s magnitude. Long form for m

persist(**kwargs)[source]

Persist the Dask Array wrapped by pint.Quantity.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.persist.

Returns:

A pint.Quantity wrapped Dask array.

Return type:

pint.Quantity

prod(axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]

Return the product of quantity elements over a given axis

Wraps np.prod().

to(other=None, *contexts, **ctx_kwargs) Quantity[_MagnitudeType][source]

Return Quantity rescaled to different units.

Parameters:
  • other (pint.Quantity, 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

Return type:

pint.Quantity

to_base_units() Quantity[_MagnitudeType][source]

Return Quantity rescaled to base units.

to_compact(unit=None) Quantity[_MagnitudeType][source]

“Return Quantity 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() Quantity[_MagnitudeType][source]

Return Quantity 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() Quantity[_MagnitudeType][source]

Return Quantity rescaled to root units.

property u: Unit

Quantity’s units. Short form for units

property units: Unit

Quantity’s units. Long form for u

visualize(**kwargs)[source]

Produce a visual representation of the Dask graph.

The graphviz library is required.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.visualize.

exception pint.RedefinitionError(name, definition_type, *, filename=None, lineno=None)[source]

Raised when a unit or prefix is redefined.

exception pint.UndefinedUnitError(*unit_names)[source]

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

class pint.Unit(*args, **kwargs)[source]

Implements a class to describe a unit supporting math operations.

default_format: str = ''

Default formatting string.

property dimensionality: UnitsContainer

returns: Dimensionality of the Unit, e.g. {length: 1, time: -1} :rtype: dict

property dimensionless: bool

Return True if the Unit 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:

The converted value as this unit

Return type:

type

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, Unit or str.

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

  • **ctx_kwargs – Values for the Context/s

Return type:

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:

The magnitude of the converted value

Return type:

type

class pint.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 base 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 – 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)

check(*args: Optional[Union[str, UnitsContainer, Unit]]) 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:

the wrapped function.

Return type:

callable

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:

a list of dimensionless quantities expressed as dicts

Return type:

list

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: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], args: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], 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:

the wrapper function.

Return type:

callable

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

exception pint.UnitStrippedWarning[source]
pint.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:

the formula as a string.

Return type:

str

pint.get_application_registry()[source]

Return the application registry. If set_application_registry() was never invoked, return a registry built using defaults_en.txt embedded in the pint package.

Return type:

pint.UnitRegistry

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

a list of dimensionless quantities expressed as dicts

Return type:

type

pint.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.set_application_registry(registry)[source]

Set the application registry, which is used for unpickling operations and when invoking pint.Quantity or pint.Unit directly.

Parameters:

registry (pint.UnitRegistry) –

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.

Return type:

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

Return type:

bool

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

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

Parameters:

other (object) –

Return type:

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

Functions and classes related to context definitions and application.

copyright:

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

license:

BSD, see LICENSE for more details.

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

Return type:

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

Return type:

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.context.ContextChain[source]

A specialized ChainMap for contexts that simplifies finding rules to transform from one dimension to another.

property graph

The graph relating

hashable()[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__.

insert_contexts(*contexts)[source]

Insert one or more contexts in reversed order the chained map. (A rule in last context will take precedence)

To facilitate the identification of the context with the matching rule, the relation_to_context dictionary of the context is used.

remove_contexts(n: int = None)[source]

Remove the last n inserted contexts from the chain.

Parameters:

n (int) – (Default value = None)

transform(src, dst, registry, value)[source]

Transform the value, finding the rule in the chained context. (A rule in last context will take precedence)

class pint.context.ContextDefinition(name: str, aliases: Tuple[str, ...], variables: Tuple[str, ...], defaults: Dict[str, Number], relations: Tuple[Tuple[int, Relation], ...], redefinitions: Tuple[Tuple[int, UnitDefinition], ...])[source]

Definition of a Context

@context[(defaults)] <canonical name> [= <alias>] [= <alias>]

# units can be redefined within the context <redefined unit> = <relation to another unit>

# can establish unidirectional relationships between dimensions <dimension 1> -> <dimension 2>: <transformation function>

# can establish bidirectionl relationships between dimensions <dimension 3> <-> <dimension 4>: <transformation function>

@end

Example:

@context(n=1) spectroscopy = sp
    # n index of refraction of the medium.
    [length] <-> [frequency]: speed_of_light / n / value
    [frequency] -> [energy]: planck_constant * value
    [energy] -> [frequency]: value / planck_constant
    # allow wavenumber / kayser
    [wavenumber] <-> [length]: 1 / value
@end
class pint.context.Relation(bidirectional: 'True', src: 'ParserHelper', dst: 'ParserHelper', tranformation: 'Callable[..., Quantity[Any]]')[source]

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.

class pint.converters.LogarithmicConverter(scale, logbase, logfactor)[source]

Converts between linear units and logarithmic units, such as dB, octave, neper or pH. Q_log = logfactor * log( Q_lin / scale ) / log(log_base)

Parameters:
  • scale (float) – unit of reference at denominator for logarithmic unit conversion

  • logbase (float) – base of logarithm used in the logarithmic unit conversion

  • logfactor (float) – factor multiplied to logarithm for unit conversion

  • inplace (bool) – controls if computation is done in place

from_reference(value, inplace=False)[source]

Converts value from the reference unit to the logarithmic unit

dBm <—— mW y dBm = 10 log10( x / 1mW )

to_reference(value, inplace=False)[source]

Converts value to the reference unit from the logarithmic unit

dBm ——> mW y dBm = 10 log10( x / 1mW )

class pint.converters.OffsetConverter(scale, offset)[source]

An affine transformation.

class pint.converters.ScaleConverter(scale)[source]

A linear transformation.

pint.definitions

Functions and classes related to unit definitions.

copyright:

2016 by Pint Authors, see AUTHORS for more details.

license:

BSD, see LICENSE for more details.

class pint.definitions.AliasDefinition(name: str, aliases: Iterable[str])[source]

Additional alias(es) for an already existing unit:

@alias <canonical name or previous alias> = <alias> [ = <alias> ] [...]

Example:

@alias meter = my_meter
classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) AliasDefinition[source]

Parse a definition.

Parameters:
Return type:

Definition or subclass of Definition

class pint.definitions.Definition(name: str, defined_symbol: Optional[str], aliases: Tuple[str, ...], converter: Optional[Union[Callable, Converter]])[source]

Base class for definitions.

Parameters:
  • name (str) – Canonical name of the unit/prefix/etc.

  • defined_symbol (str or None) – A short name or symbol for the definition.

  • aliases (iterable of str) – Other names for the unit/prefix/etc.

  • converter (callable or Converter or None) –

classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) Definition[source]

Parse a definition.

Parameters:
Return type:

Definition or subclass of Definition

class pint.definitions.DimensionDefinition(name: str, defined_symbol: Optional[str], aliases: Tuple[str, ...], converter: Optional[Union[Callable, Converter]], reference: Optional[UnitsContainer] = None, is_base: bool = False)[source]

Definition of a dimension:

[dimension name] = <relation to other dimensions>

Example:

[density] = [mass] / [volume]
classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) DimensionDefinition[source]

Parse a definition.

Parameters:
Return type:

Definition or subclass of Definition

class pint.definitions.PrefixDefinition(name: str, defined_symbol: Optional[str], aliases: Tuple[str, ...], converter: Optional[Union[Callable, Converter]])[source]

Definition of a prefix:

<prefix>- = <amount> [= <symbol>] [= <alias>] [ = <alias> ] [...]

Example:

deca- =  1e+1  = da- = deka-
classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) PrefixDefinition[source]

Parse a definition.

Parameters:
Return type:

Definition or subclass of Definition

class pint.definitions.PreprocessedDefinition(name: str, symbol: Optional[str], aliases: Tuple[str, ...], value: str, rhs_parts: Tuple[str, ...])[source]

Splits a definition into the constitutive parts.

A definition is given as a string with equalities in a single line:

---------------> rhs
a = b = c = d = e
|   |   |   -------> aliases (optional)
|   |   |
|   |   -----------> symbol (use "_" for no symbol)
|   |
|   ---------------> value
|
-------------------> name
class pint.definitions.UnitDefinition(name: str, defined_symbol: Optional[str], aliases: Tuple[str, ...], converter: Optional[Union[Callable, Converter]], reference: Optional[UnitsContainer] = None, is_base: bool = False)[source]

Definition of a unit:

<canonical name> = <relation to another unit or dimension> [= <symbol>] [= <alias>] [ = <alias> ] [...]

Example:

millennium = 1e3 * year = _ = millennia
Parameters:
  • reference (UnitsContainer) – Reference units.

  • is_base (bool) – Indicates if it is a base unit.

classmethod from_string(definition: ~typing.Union[str, ~pint.definitions.PreprocessedDefinition], non_int_type: type = <class 'float'>) UnitDefinition[source]

Parse a definition.

Parameters:
Return type:

Definition or subclass of Definition

pint.definitions.numeric_parse(s: str, non_int_type: type = <class 'float'>)[source]

Try parse a string into a number (without using eval).

Parameters:
  • s (str) –

  • non_int_type (type) –

Return type:

Number

Raises:

_NotNumeric – If the string cannot be parsed as a number.

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.DefinitionSyntaxError(msg, *, filename=None, lineno=None)[source]

Raised when a textual definition has a syntax error.

exception pint.errors.DimensionalityError(units1, units2, dim1='', dim2='', *, extra_msg='')[source]

Raised when trying to convert between incompatible units.

exception pint.errors.LogarithmicUnitCalculusError[source]

Raised on inappropriate operations with logarithmic units.

exception pint.errors.OffsetUnitCalculusError[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, definition_type, *, filename=None, lineno=None)[source]

Raised when a unit or prefix is redefined.

exception pint.errors.UndefinedUnitError(*unit_names)[source]

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

exception pint.errors.UnitStrippedWarning[source]

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:

the formula as a string.

Return type:

str

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

copyright:

2016 by Pint Authors, see AUTHORS for more details.

license:

BSD, see LICENSE for more details.

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

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, op_priority={'': 1, '%': 1, '*': 1, '**': 3, '+': 0, '-': 0, '/': 1, '//': 1, '^': 3, 'unary': 2}, index=0, depth=0, prev_op=None)[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.quantity

copyright:

2016 by Pint Authors, see AUTHORS for more details.

license:

BSD, see LICENSE for more details.

class pint.quantity.Quantity(value: str, units: Optional[UnitLike] = None)[source]
class pint.quantity.Quantity(value: Sequence, units: Optional[UnitLike] = None)
class pint.quantity.Quantity(value: Quantity[Magnitude], units: Optional[UnitLike] = None)
class pint.quantity.Quantity(value: Magnitude, units: Optional[UnitLike] = None)

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

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

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

check(dimension: UnitLike) bool[source]

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

compute(**kwargs)[source]

Compute the Dask array wrapped by pint.Quantity.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.compute.

Returns:

A pint.Quantity wrapped numpy array.

Return type:

pint.Quantity

default_format: str = ''

Default formatting string.

property dimensionality: UnitsContainerT

returns: Dimensionality of the Quantity, e.g. {length: 1, time: -1} :rtype: dict

dot(b)[source]

Dot product of two arrays.

Wraps np.dot().

classmethod from_list(quant_list: List[Quantity], units=None) Quantity[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.Quantity) – list of pint.Quantity

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

Return type:

pint.Quantity

classmethod from_sequence(seq: Sequence[Quantity], units=None) Quantity[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.Quantity) – sequence of pint.Quantity

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

Return type:

pint.Quantity

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, Unit or str.

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

  • **ctx_kwargs – Values for the Context/s

Return type:

bool

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

Inplace rescale to different units.

Parameters:
  • other (pint.Quantity, 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 Quantity rescaled to base units.

ito_reduced_units() None[source]

Return Quantity 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 Quantity rescaled to root units.

property m: _MagnitudeType

Quantity’s magnitude. Short form for magnitude

m_as(units) _MagnitudeType[source]

Quantity’s magnitude expressed in particular units.

Parameters:

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

property magnitude: _MagnitudeType

Quantity’s magnitude. Long form for m

persist(**kwargs)[source]

Persist the Dask Array wrapped by pint.Quantity.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.persist.

Returns:

A pint.Quantity wrapped Dask array.

Return type:

pint.Quantity

prod(axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]

Return the product of quantity elements over a given axis

Wraps np.prod().

to(other=None, *contexts, **ctx_kwargs) Quantity[_MagnitudeType][source]

Return Quantity rescaled to different units.

Parameters:
  • other (pint.Quantity, 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

Return type:

pint.Quantity

to_base_units() Quantity[_MagnitudeType][source]

Return Quantity rescaled to base units.

to_compact(unit=None) Quantity[_MagnitudeType][source]

“Return Quantity 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() Quantity[_MagnitudeType][source]

Return Quantity 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() Quantity[_MagnitudeType][source]

Return Quantity rescaled to root units.

property u: Unit

Quantity’s units. Short form for units

property units: Unit

Quantity’s units. Long form for u

visualize(**kwargs)[source]

Produce a visual representation of the Dask graph.

The graphviz library is required.

Parameters:

**kwargs (dict) – Any keyword arguments to pass to dask.visualize.

pint.registry

Defines the Registry, a class to contain units and their relations.

The module actually defines 5 registries with different capabilities:

  • BaseRegistry: Basic unit definition and querying.

    Conversion between multiplicative units.

  • NonMultiplicativeRegistry: Conversion between non multiplicative (offset) units.

    (e.g. Temperature)

    • Inherits from BaseRegistry

  • ContextRegisty: Conversion between units with different dimensions according

    to previously established relations (contexts) - e.g. in spectroscopy, conversion between frequency and energy is possible. May also override conversions between units on the same dimension - e.g. different rounding conventions.

    • Inherits from BaseRegistry

  • SystemRegistry: Group unit and changing of base units.

    (e.g. in MKS, meter, kilogram and second are base units.)

    • Inherits from BaseRegistry

  • UnitRegistry: Combine all previous capabilities, it is exposed by Pint.

copyright:

2016 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.BaseRegistry(*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: T, src: QuantityOrUnitLike, dst: QuantityOrUnitLike, inplace: bool = False) 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:

converted value

Return type:

type

property default_format: str

Default formatting string for quantities.

define(definition: Union[str, Definition]) None[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 base 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:

multiplicative factor, base units

Return type:

Number, pint.Unit

get_dimensionality(input_units) UnitsContainerT[source]

Convert unit or dict of units or dimensions to a dict of base 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: UnitLike, check_nonmult: bool = True) Tuple[Number, Unit][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:

multiplicative factor, base units

Return type:

Number, pint.Unit

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 – The objects to check against each other. Treated as dimensionless if not a Quantity, Unit or str.

  • 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

Return type:

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)

non_int_type

Numerical type used for non integer values.

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:

all non-equivalent combinations of (prefix, unit name, suffix)

Return type:

tuple of tuples (str, str, str)

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.

Return type:

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.registry.ContextCacheOverlay(registry_cache: RegistryCache)[source]

Layer on top of the base UnitRegistry cache, specific to a combination of active contexts which contain unit redefinitions.

class pint.registry.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.

add_context(context: Context) 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) ContextManager[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
>>> ureg = pint.UnitRegistry()
>>> ureg.add_context(pint.Context('one'))
>>> ureg.add_context(pint.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: 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, 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) 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[[F], 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:

:param name: name of the context.
:param \*\*kwargs: keyword arguments for the context
Returns:

the wrapped function.

Return type:

callable

Example

>>> @ureg.with_context('sp')
... def my_cool_fun(wavelength):
...     print('This wavelength is equivalent to: %s', wavelength.to('terahertz'))
class pint.registry.DefaultsDefinition(content: Tuple[Tuple[str, str], ...])[source]

Definition for the @default directive

class pint.registry.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 base units in multiplications.

default_as_delta

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

class pint.registry.RegistryCache[source]

Cache to speed up unit registries

dimensional_equivalents: Dict[UnitsContainer, Set[str]]

Maps dimensionality (UnitsContainer) to Units (str)

dimensionality: Dict[UnitsContainer, UnitsContainer]

Maps dimensionality (UnitsContainer) to Units (UnitsContainer)

parse_unit: Dict[str, UnitsContainer]

Cache the unit name associated to user input. (‘mV’ -> ‘millivolt’)

root_units

Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer)

class pint.registry.RegistryMeta[source]

This is just to call after_init at the right time instead of asking the developer to do it when subclassing.

class pint.registry.SystemRegistry(*args, **kwargs)[source]

Handle of Systems and Groups.

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 and groups.

  • List systems

  • Get or get the default system.

  • Parse @system and @group directive.

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 base units.

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

Unlike BaseRegistry, 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:

multiplicative factor, base units

Return type:

type

get_group(name: str, create_if_needed: bool = True) 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

Return type:

type

get_system(name: str, create_if_needed: bool = True) 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:

System

Return type:

type

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 base 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 – 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)

check(*args: Optional[Union[str, UnitsContainer, Unit]]) 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:

the wrapped function.

Return type:

callable

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:

a list of dimensionless quantities expressed as dicts

Return type:

list

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: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], args: Optional[Union[str, Unit, Iterable[Optional[Union[str, Unit]]]]], 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:

the wrapper function.

Return type:

callable

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

the wrapped function.

Return type:

callable

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[[...], 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:

the wrapper function.

Return type:

callable

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

Functions and classes related to system definitions and conversions.

copyright:

2016 by Pint Authors, see AUTHORS for more details.

license:

BSD, see LICENSE for more details.

class pint.systems.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'>) 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.systems.GroupDefinition(name: str, units: Tuple[Tuple[int, UnitDefinition], ...], using_group_names: Tuple[str, ...])[source]

Definition of a group.

@group <name> [using <group 1>, …, <group N>]

<definition 1> … <definition N>

@end

Example:

@group AvoirdupoisUS using Avoirdupois
    US_hundredweight = hundredweight = US_cwt
    US_ton = ton
    US_force_ton = force_ton = _ = US_ton_force
@end
classmethod from_lines(lines, non_int_type=<class 'float'>)[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.

class pint.systems.System(*args, **kwargs)[source]

A system is a Group plus a set of base 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.systems.SystemDefinition(name: str, unit_replacements: Tuple[Tuple[int, str, str], ...], using_group_names: Tuple[str, ...])[source]

Definition of a System:

@system <name> [using <group 1>, …, <group N>]

<rule 1> … <rule N>

@end

The syntax for the rule is:

new_unit_name : old_unit_name

where:
  • old_unit_name: a root unit part which is going to be removed from the system.

  • new_unit_name: a non root unit which is going to replace the old_unit.

If the new_unit_name and the old_unit_name, the later and the colon can be omitted.

pint.unit

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.

class pint.unit.Unit(*args, **kwargs)[source]

Implements a class to describe a unit supporting math operations.

default_format: str = ''

Default formatting string.

property dimensionality: UnitsContainer

returns: Dimensionality of the Unit, e.g. {length: 1, time: -1} :rtype: dict

property dimensionless: bool

Return True if the Unit 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:

The converted value as this unit

Return type:

type

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, Unit or str.

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

  • **ctx_kwargs – Values for the Context/s

Return type:

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:

The magnitude of the converted value

Return type:

type

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.BlockIterator(line_iterator)[source]

Like SourceIterator but stops when it finds @end’ It also raises an error if another ‘@’ directive is found inside.

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:

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.

Return type:

type

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.SourceIterator(sequence, filename=None, is_resource=False)[source]

Iterator to facilitate reading the definition files.

Accepts any sequence (like a list of lines, a file or another SourceIterator)

The iterator yields the line number and line (skipping comments and empty lines) and stripping white spaces.

for lineno, line in SourceIterator(sequence):

# do something here

block_iter()[source]

Iterate block including header.

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)

Return type:

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

column echelon form, transformed identity matrix, swapped rows

Return type:

type

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[BaseRegistry] = None) UnitsContainer[source]

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

Parameters:
  • unit_like (Union[UnitLike, Quantity]) – Quantity or Unit to infer the base units from.

  • registry (Optional[BaseRegistry]) – If provided, uses the registry’s UnitsContainer and parse_unit_name. If None, uses the registry attached to unit_like.

Return type:

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:

a list of dimensionless quantities expressed as dicts

Return type:

type

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:

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

Return type:

type

pint.util.to_units_container(unit_like: Union[UnitLike, Quantity], registry: Optional[BaseRegistry] = 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]