Skip to main content
`Ctrl`+`K`

# Base API

These are the classes, exceptions and functions that you will most likely use.

## Most important classes

class pint.UnitRegistry(*args: Any, **kwargs: Any)

  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 string to load the default definition file. (default) None to leave the UnitRegistry empty.

    - force_ndarray (`bool`) – convert any input, scalar or not to a numpy.ndarray. (Default: False)

    - force_ndarray_like (`bool`) – convert all inputs other than duck arrays to a numpy.ndarray. (Default: False)

    - default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts. (Default: False)

    - autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their plain units in multiplicative context. If False no conversion happens. (Default: False)

    - on_redefinition (`str`) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’ (Default: ‘raise’)

    - auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations. (Default: False)

    - autoconvert_to_preferred – If True, converts preferred units on appropriate operations. (Default: False)

    - preprocessors – list of callables which are iteratively ran on any input expression or unit string or None for no preprocessor. (Default=None)

    - fmt_locale – locale identifier string, used in format_babel or None. (Default=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: str | UnitsContainer | Unit | None) → Callable[[F], F]

    Decorator to for quantity type checking for function inputs.

    Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.

    The wrapper function raises:

      - pint.DimensionalityError if an argument doesn’t match the required dimensions.

    uregUnitRegistry

      a UnitRegistry instance.

    argsstr or UnitContainer or None

      Dimensions of each of the input arguments. Use None to skip argument conversion.

    Returns:

      `callable()` – the wrapped function.

    Raises:

      - TypeError – If the number of given dimensions does not match the number of function parameters.

      - ValueError – If the any of the provided dimensions cannot be parsed as a dimension.

  pi_theorem(quantities)

    Builds dimensionless quantities using the Buckingham π theorem

    Parameters:

      quantities (`dict`) – mapping between variable name and units

    Returns:

      `list` – a list of dimensionless quantities expressed as dicts

  setup_matplotlib(enable: bool = True) → None

    Set up handlers for matplotlib’s unit support.

    Parameters:

      enable (`bool`) – whether support should be enabled or disabled (Default value = True)

  wraps(ret: str | Unit | Iterable[str | Unit | None] | None, args: str | Unit | Iterable[str | Unit | None] | None, strict: bool = True) → Callable[[Callable[..., Any]], Callable[..., Quantity]]

    Wraps a function to become pint-aware.

    Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.

    The value returned by the wrapped function will be converted to the units specified in ret.

    Parameters:

      - ureg (`pint.UnitRegistry`) – a UnitRegistry instance.

      - ret (`str`, `pint.Unit`, or iterable of `str` or `pint.Unit`) – Units of each of the return values. Use None to skip argument conversion.

      - args (`str`, `pint.Unit`, or iterable of `str` or `pint.Unit`) – Units of each of the input arguments. Use None to skip argument conversion.

      - strict (`bool`) – Indicates that only quantities are accepted. (Default value = True)

    Returns:

      `callable()` – the wrapper function.

    Raises:

      TypeError – if the number of given arguments does not match the number of function parameters. if any of the provided arguments is not a unit a string or Quantity

class pint.Quantity(value: MagnitudeT, units: UnitLike | None = None)
class pint.Quantity(value: str, units: UnitLike | None = None)
class pint.Quantity(value: Sequence[ScalarT], units: UnitLike | None = None)
class pint.Quantity(value: PlainQuantity[Any], units: UnitLike | None = None)
  check(dimension: str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit')) → bool

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

  compute(**kwargs)

    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.

  property dimensionality: UnitsContainerT
    Returns:

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

  dot(b)

    Dot product of two arrays.

    Wraps np.dot().

  classmethod from_list(quant_list: list[PlainQuantity[MagnitudeT]], units=None) → PlainQuantity[MagnitudeT]

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

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

    Parameters:

      - quant_list (`list` of `pint.PlainQuantity`) – list of pint.PlainQuantity

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

    Returns:

      `pint.PlainQuantity`

  classmethod from_sequence(seq: Sequence[PlainQuantity[MagnitudeT]], units=None) → PlainQuantity[MagnitudeT]

    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: str | Context, **ctx_kwargs: Any) → bool

    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: TypeAliasForwardRef('~pint.Quantity') | str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit') | None = None, *contexts, **ctx_kwargs) → None

    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

    Return PlainQuantity rescaled to plain units.

  ito_preferred(preferred_units: list[UnitLike] | None = None) → PlainQuantity

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

    Note: this feature crashes on Python >= 3.12 (issue #2121).

    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, 'watt * second')>

  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

    Return PlainQuantity rescaled to root units.

  property m: MagnitudeT

    PlainQuantity’s magnitude. Short form for magnitude

  m_as(units) → MagnitudeT

    PlainQuantity’s magnitude expressed in particular units.

    Parameters:

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

  property magnitude: MagnitudeT

    PlainQuantity’s magnitude. Long form for m

  persist(**kwargs)

    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.

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

    Return the product of quantity elements over a given axis

    Wraps np.prod().

  to(other: TypeAliasForwardRef('~pint.Quantity') | str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit') | None = None, *contexts, **ctx_kwargs) → Self

    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() → PlainQuantity[MagnitudeT]

    Return PlainQuantity rescaled to plain units.

  to_compact(unit: UnitsContainer | None = 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: list[UnitLike] | None = None) → PlainQuantity

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

    Note: this feature crashes on Python >= 3.12 (issue #2121).

    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, 'watt * second')>

  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() → PlainQuantity[MagnitudeT]

    Return PlainQuantity rescaled to root units.

  property u: Unit

    PlainQuantity’s units. Short form for units

  unit_items() → Iterable[tuple[str, float | int | Decimal | Fraction]]

    A view of the unit items.

  property units: Unit

    PlainQuantity’s units. Long form for u

  visualize(**kwargs)

    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.Unit(*args, **kwargs)
  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')

    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: str | Context, **ctx_kwargs: Any) → bool

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

    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.Measurement(value, error=<object object>, units=<object object>)

  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

  check(dimension: str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit')) → bool

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

  property dimensionality: UnitsContainerT
    Returns:

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

  classmethod from_list(quant_list: list[PlainQuantity[MagnitudeT]], units=None) → PlainQuantity[MagnitudeT]

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

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

    Parameters:

      - quant_list (`list` of `pint.PlainQuantity`) – list of pint.PlainQuantity

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

    Returns:

      `pint.PlainQuantity`

  classmethod from_sequence(seq: Sequence[PlainQuantity[MagnitudeT]], units=None) → PlainQuantity[MagnitudeT]

    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: str | Context, **ctx_kwargs: Any) → bool

    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: TypeAliasForwardRef('~pint.Quantity') | str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit') | None = None, *contexts, **ctx_kwargs) → None

    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

    Return PlainQuantity rescaled to plain units.

  ito_preferred(preferred_units: list[UnitLike] | None = None) → PlainQuantity

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

    Note: this feature crashes on Python >= 3.12 (issue #2121).

    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, 'watt * second')>

  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

    Return PlainQuantity rescaled to root units.

  property m: MagnitudeT

    PlainQuantity’s magnitude. Short form for magnitude

  m_as(units) → MagnitudeT

    PlainQuantity’s magnitude expressed in particular units.

    Parameters:

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

  property magnitude: MagnitudeT

    PlainQuantity’s magnitude. Long form for m

  to(other: TypeAliasForwardRef('~pint.Quantity') | str | dict[str, float | int | Decimal | Fraction] | TypeAliasForwardRef('~pint.UnitsContainer') | TypeAliasForwardRef('~pint.Unit') | None = None, *contexts, **ctx_kwargs) → Self

    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() → PlainQuantity[MagnitudeT]

    Return PlainQuantity rescaled to plain units.

  to_compact(unit: UnitsContainer | None = 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: list[UnitLike] | None = None) → PlainQuantity

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

    Note: this feature crashes on Python >= 3.12 (issue #2121).

    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, 'watt * second')>

  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() → PlainQuantity[MagnitudeT]

    Return PlainQuantity rescaled to root units.

  property u: Unit

    PlainQuantity’s units. Short form for units

  unit_items() → Iterable[tuple[str, float | int | Decimal | Fraction]]

    A view of the unit items.

  property units: Unit

    PlainQuantity’s units. Long form for u

## Exceptions and warnings

exception pint.PintError

  Base exception for all Pint errors.

exception pint.DefinitionSyntaxError(msg: str)

  Raised when a textual definition has a syntax error.

exception pint.LogarithmicUnitCalculusError(units1: Any, units2: Any | None = None)

  Raised on inappropriate operations with logarithmic units.

exception pint.DimensionalityError(units1: Any, units2: Any, dim1: str = '', dim2: str = '', extra_msg: str = '')

  Raised when trying to convert between incompatible units.

exception pint.OffsetUnitCalculusError(units1: Any, units2: Any | None = None)

  Raised on ambiguous operations with offset units.

exception pint.RedefinitionError(name: str, definition_type: type)

  Raised when a unit or prefix is redefined.

exception pint.UndefinedUnitError(unit_names: str | Iterable[str])

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

exception pint.UnitStrippedWarning(msg: str)

## Sharing registry among packages

pint.get_application_registry()

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

  Returns:

    `pint.UnitRegistry`

pint.set_application_registry(registry)

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

  Parameters:

    registry (`pint.UnitRegistry`)

## Other functions

pint.formatter(numerator: Iterable[tuple[str, Number]], denominator: Iterable[tuple[str, Number]], as_ratio: bool = True, single_denominator: bool = False, product_fmt: str = ' * ', division_fmt: str = ' / ', power_fmt: str = '{} ** {}', parentheses_fmt: str = '({0})', exp_call: FORMATTER = <built-in method format of str object>) → str

  Format a list of (name, exponent) pairs.

  Parameters:

    - items (`list`) – a list of (name, exponent) pairs.

    - as_ratio (`bool`, optional) – True to display as ratio, False as negative powers. (Default value = True)

    - single_denominator (`bool`, optional) – all with terms with negative exponents are collected together. (Default value = False)

    - product_fmt (`str`) – the format used for multiplication. (Default value = “ * “)

    - division_fmt (`str`) – the format used for division. (Default value = “ / “)

    - power_fmt (`str`) – the format used for exponentiation. (Default value = “{} ** {}”)

    - parentheses_fmt (`str`) – the format used for parenthesis. (Default value = “({0})”)

    - exp_call (`callable()`) – (Default value = lambda x: f”{x:n}”)

  Returns:

    `str` – the formula as a string.

pint.register_unit_format(name: str)

  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.pi_theorem(quantities: dict[str, Any], registry: UnitRegistry | None = None)

  Builds dimensionless quantities using the Buckingham π theorem

  Parameters:

    - quantities (`dict`) – mapping between variable name and units

    - registry – (default value = None)

  Returns:

    `type` – a list of dimensionless quantities expressed as dicts

class pint.Context(name: str | None = None, aliases: tuple[str, ...] = (), defaults: dict[str, Any] | None = None)

  A specialized container that defines transformation functions from one dimension to another. Each Dimension are specified using a UnitsContainer. Simple transformation are given with a function taking a single parameter.

  Conversion functions may take optional keyword arguments and the context can have default values for these arguments.

  Additionally, a context may host redefinitions.

  A redefinition must be performed among units that already exist in the registry. It cannot change the dimensionality of a unit. The symbol and aliases are automatically inherited from the registry.

  See ContextDefinition for the definition file syntax.

  Parameters:

    - name (`str` or `None`, optional) – Name of the context (must be unique within the registry). Use None for anonymous Context. (Default value = None).

    - aliases (iterable of `str`) – Other names for the context.

    - defaults (`None` or `dict`) – Maps variable names to values.

  Example

      >>> from pint.util import UnitsContainer
      >>> from pint import Context, UnitRegistry
      >>> ureg = UnitRegistry()
      >>> timedim = UnitsContainer({"[time]": 1})
      >>> spacedim = UnitsContainer({"[length]": 1})
      >>> def time_to_len(ureg, time):
      ...     "Time to length converter"
      ...     return 3.0 * 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.0 * 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")