API facets reference#

Registry functionality is divided into facet. Each provides classes and functions specific to a particular purpose. They expose at least a Registry, and in certain cases also a Quantity, Unit and other objects.

The default UnitRegistry inherits from all of them.

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

class pint.facets.plain.GenericPlainRegistry(*args: Any, **kwargs: Any)[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.

  • autoconvert_to_preferred – If True, converts preferred units 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.

autoconvert_to_preferred#

Determines if units will be converted to preffered 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
Returns

type – converted value

property default_format: str#

Default formatting string for quantities.

define(definition: Union[str, type]) 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: Union[UnitsContainer, str], check_nonmult: bool = True, system=None) tuple[Scalar, UnitT][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: UnitLike) 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: UnitLike, check_nonmult: bool = True) tuple[Scalar, UnitT][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: Union[collections.abc.Iterable[str], str, pathlib.Path], 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)

mpl_formatter#

sets the formatter used when plotting with matplotlib

parse_expression(input_string: str, case_sensitive: Optional[bool] = None, **values: Any) pint.facets.plain.registry.QuantityT[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, optional – If true, a case sensitive matching of the unit name will be done in the registry. If false, a case INsensitive matching of the unit name will be done in the registry. (Default value = None, which uses registry setting)

  • **values – Other string that will be parsed using the Quantity constructor on their corresponding value.

parse_pattern(input_string: str, pattern: str, case_sensitive: Optional[bool] = None, 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, optional – If true, a case sensitive matching of the unit name will be done in the registry. If false, a case INsensitive matching of the unit name will be done in the registry. (Default value = None, which uses registry setting)

  • many, optional – 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) pint.facets.plain.registry.UnitT[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.PlainQuantity(value: pint.facets.plain.quantity.MagnitudeT, units: Optional[UnitLike] = None)[source]#
class pint.facets.plain.PlainQuantity(value: str, units: Optional[UnitLike] = None)
class pint.facets.plain.PlainQuantity(value: collections.abc.Sequence[pint.facets.plain.quantity.ScalarT], units: Optional[UnitLike] = None)
class pint.facets.plain.PlainQuantity(value: pint.facets.plain.quantity.PlainQuantity[Any], 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.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: UnitLike) 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[MagnitudeT]], units=None) pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.MagnitudeT][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: collections.abc.Sequence[pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.MagnitudeT]], units=None) pint.facets.plain.quantity.PlainQuantity[pint.facets.plain.quantity.MagnitudeT][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: Optional[QuantityOrUnitLike] = 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_preferred(preferred_units: Optional[list[UnitLike]] = None) PlainQuantity#

Return Quantity converted to a unit composed of the preferred units.

Examples

>>> import pint
>>> ureg = pint.UnitRegistry()
>>> (1*ureg.acre).to_preferred([ureg.meters])
<Quantity(4046.87261, 'meter ** 2')>
>>> (1*(ureg.force_pound*ureg.m)).to_preferred([ureg.W])
<Quantity(4.44822162, 'second * watt')>
ito_reduced_units() None#

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.facets.plain.quantity.MagnitudeT#

PlainQuantity’s magnitude. Short form for magnitude

m_as(units) pint.facets.plain.quantity.MagnitudeT[source]#

PlainQuantity’s magnitude expressed in particular units.

Parameters

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

property magnitude: pint.facets.plain.quantity.MagnitudeT#

PlainQuantity’s magnitude. Long form for m

to(other: Optional[QuantityOrUnitLike] = None, *contexts, **ctx_kwargs) PlainQuantity[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.facets.plain.quantity.MagnitudeT][source]#

Return PlainQuantity rescaled to plain units.

to_compact(unit: Optional[UnitsContainer] = None) PlainQuantity#

“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_preferred(preferred_units: Optional[list[UnitLike]] = None) PlainQuantity#

Return Quantity converted to a unit composed of the preferred units.

Examples

>>> import pint
>>> ureg = pint.UnitRegistry()
>>> (1*ureg.acre).to_preferred([ureg.meters])
<Quantity(4046.87261, 'meter ** 2')>
>>> (1*(ureg.force_pound*ureg.m)).to_preferred([ureg.W])
<Quantity(4.44822162, 'second * watt')>
to_reduced_units() PlainQuantity#

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.facets.plain.quantity.MagnitudeT][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: Any, **kwargs: Any)[source]#
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

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: Optional[str], aliases: tuple[str, ...], converter: Optional[Converter], reference: Optional[UnitsContainer])[source]#

Definition of a unit.

aliases: tuple[str, ...]#

additional names for the same unit

defined_symbol: Optional[str]#

canonical symbol

property is_base: bool#

Indicates if it is a base unit.

reference: Optional[UnitsContainer]#

Reference units.

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.GenericNonMultiplicativeRegistry(*args: Any, **kwargs: Any)[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.

default_as_delta#

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

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

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.FormattingQuantity(value: pint.facets.plain.quantity.MagnitudeT, units: Optional[UnitLike] = None)[source]#
class pint.facets.formatting.FormattingQuantity(value: str, units: Optional[UnitLike] = None)
class pint.facets.formatting.FormattingQuantity(value: collections.abc.Sequence[pint.facets.plain.quantity.ScalarT], units: Optional[UnitLike] = None)
class pint.facets.formatting.FormattingQuantity(value: pint.facets.plain.quantity.PlainQuantity[Any], units: Optional[UnitLike] = None)
class pint.facets.formatting.FormattingRegistry(*args: Any, **kwargs: Any)[source]#
class pint.facets.formatting.FormattingUnit(*args, **kwargs)[source]#
class pint.facets.formatting.GenericFormattingRegistry(*args: Any, **kwargs: Any)[source]#

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.GenericNumpyRegistry(*args: Any, **kwargs: Any)[source]#
class pint.facets.numpy.NumpyRegistry(*args: Any, **kwargs: Any)[source]#

pint.facets.dask#

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.DaskQuantity(value: pint.facets.plain.quantity.MagnitudeT, units: Optional[UnitLike] = None)[source]#
class pint.facets.dask.DaskQuantity(value: str, units: Optional[UnitLike] = None)
class pint.facets.dask.DaskQuantity(value: collections.abc.Sequence[pint.facets.plain.quantity.ScalarT], units: Optional[UnitLike] = None)
class pint.facets.dask.DaskQuantity(value: pint.facets.plain.quantity.PlainQuantity[Any], units: Optional[UnitLike] = None)
compute(**kwargs)[source]#

Compute the Dask array wrapped by pint.PlainQuantity.

Parameters

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

Returns

pint.PlainQuantity – A pint.PlainQuantity wrapped numpy array.

persist(**kwargs)[source]#

Persist the Dask Array wrapped by pint.PlainQuantity.

Parameters

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

Returns

pint.PlainQuantity – A pint.PlainQuantity wrapped Dask array.

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.

class pint.facets.dask.DaskRegistry(*args: Any, **kwargs: Any)[source]#
class pint.facets.dask.DaskUnit(*args, **kwargs)[source]#
class pint.facets.dask.GenericDaskRegistry(*args: Any, **kwargs: Any)[source]#

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.GenericMeasurementRegistry(*args: Any, **kwargs: Any)[source]#
class pint.facets.measurement.MeasurementQuantity(value: pint.facets.plain.quantity.MagnitudeT, units: Optional[UnitLike] = None)[source]#
class pint.facets.measurement.MeasurementQuantity(value: str, units: Optional[UnitLike] = None)
class pint.facets.measurement.MeasurementQuantity(value: collections.abc.Sequence[pint.facets.plain.quantity.ScalarT], units: Optional[UnitLike] = None)
class pint.facets.measurement.MeasurementQuantity(value: pint.facets.plain.quantity.PlainQuantity[Any], units: Optional[UnitLike] = None)
class pint.facets.measurement.MeasurementRegistry(*args: Any, **kwargs: Any)[source]#

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.GenericGroupRegistry(*args: Any, **kwargs: Any)[source]#

Handle of Groups.

Group units

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

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

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.GroupQuantity(value: pint.facets.plain.quantity.MagnitudeT, units: Optional[UnitLike] = None)[source]#
class pint.facets.group.GroupQuantity(value: str, units: Optional[UnitLike] = None)
class pint.facets.group.GroupQuantity(value: collections.abc.Sequence[pint.facets.plain.quantity.ScalarT], units: Optional[UnitLike] = None)
class pint.facets.group.GroupQuantity(value: pint.facets.plain.quantity.PlainQuantity[Any], units: Optional[UnitLike] = None)
class pint.facets.group.GroupRegistry(*args: Any, **kwargs: Any)[source]#
class pint.facets.group.GroupUnit(*args, **kwargs)[source]#

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.GenericSystemRegistry(*args: Any, **kwargs: Any)[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.

get_base_units(input_units: Union[UnitLike, Quantity], check_nonmult: bool = True, system: Optional[Union[str, objects.System]] = 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

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: Any, **kwargs: Any)[source]#

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.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: Any, **kwargs: Any)[source]#
class pint.facets.context.GenericContextRegistry(*args: Any, **kwargs: Any)[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: 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: str, **kwargs: Any) Generator[pint.facets.context.registry.GenericContextRegistry[pint.facets.plain.registry.QuantityT, pint.facets.plain.registry.UnitT], None, None][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: Any) 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: str, **kwargs: Any) 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'))