Skip to main content
`Ctrl`+`K`

# UnitBase

class astropy.units.UnitBase

  Bases: `object`

  Abstract base class for units.

  Most of the arithmetic operations on units are defined in this base class.

  Should not be instantiated by users directly.

  Attributes Summary

  `bases` | The bases of the unit.
  `cgs` | The unit expressed in terms of CGS units.
  `physical_type` | Physical type(s) dimensionally compatible with the unit.
  `powers` | The powers of the bases of the unit.
  `scale` | The scale of the unit.
  `si` | The unit expressed in terms of SI units.

  Methods Summary

  `compose`([equivalencies, units, max_depth, ...]) | Return the simplest possible composite unit(s) that represent the given unit.
  `decompose`([bases]) | Return a unit object composed of only irreducible units.
  `find_equivalent_units`([equivalencies, ...]) | Return a list of all the units that are the same type as `self`.
  `get_converter`(other[, equivalencies]) | Create a function that converts values from this unit to another.
  `in_units`(other[, value, equivalencies]) |
  `is_equivalent`(other[, equivalencies]) | Check whether this unit is equivalent to `other`.
  `is_unity`() | Check whether the unit is unscaled and dimensionless.
  `to`(other[, value, equivalencies]) | Return the converted values in the specified unit.
  `to_string`([format, deprecations]) | Output the unit in the given format as a string.
  `to_system`(system) | Convert this unit into ones belonging to the given system.

  Attributes Documentation

  bases

    The bases of the unit.

  cgs

    The unit expressed in terms of CGS units.

  physical_type

    Physical type(s) dimensionally compatible with the unit.

    Returns:
      `PhysicalType`

        A representation of the physical type(s) of a unit.

    Examples

        >>> from astropy import units as u
        >>> u.m.physical_type
        PhysicalType('length')
        >>> (u.m ** 2 / u.s).physical_type
        PhysicalType({'diffusivity', 'kinematic viscosity'})

    Physical types can be compared to other physical types (recommended in packages) or to strings.

        >>> area = (u.m ** 2).physical_type
        >>> area == u.m.physical_type ** 2
        True
        >>> area == "area"
        True

    `PhysicalType` objects can be used for dimensional analysis.

        >>> number_density = u.m.physical_type ** -3
        >>> velocity = (u.m / u.s).physical_type
        >>> number_density * velocity
        PhysicalType('particle flux')

  powers

    The powers of the bases of the unit.

  scale

    The scale of the unit.

  si

    The unit expressed in terms of SI units.

  Methods Documentation

  compose(equivalencies=[], units=None, max_depth=2, include_prefix_units=None)

    Return the simplest possible composite unit(s) that represent the given unit. Since there may be multiple equally simple compositions of the unit, a list of units is always returned.

    Parameters:
      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to also list. See Equivalencies. This list is in addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies.

      units `set` of `Unit`, optional

        If not provided, any known units may be used to compose into. Otherwise, `units` is a dict, module or sequence containing the units to compose into.

      max_depth `python:int`, optional

        The maximum recursion depth to use when composing into composite units.

      include_prefix_units bool, optional

        When `True`, include prefixed units in the result. Default is `True` if a sequence is passed in to `units`, `False` otherwise.

    Returns:
      units `python:list` of `CompositeUnit`

        A list of candidate compositions. These will all be equally simple, but it may not be possible to automatically determine which of the candidates are better.

  decompose(bases=())

    Return a unit object composed of only irreducible units.

    Parameters:
      bases python:sequence of `UnitBase`, optional

        The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a `UnitsError` if it’s not possible to do so.

    Returns:
      unit `CompositeUnit`

        New object containing only irreducible unit objects.

  find_equivalent_units(equivalencies=[], units=None, include_prefix_units=False)

    Return a list of all the units that are the same type as `self`.

    Parameters:
      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to also list. See Equivalencies. Any list given, including an empty one, supersedes global defaults that may be in effect (as set by `set_enabled_equivalencies`)

      units `set` of `Unit`, optional

        If not provided, all defined units will be searched for equivalencies. Otherwise, may be a dict, module or sequence containing the units to search for equivalencies.

      include_prefix_units bool, optional

        When `True`, include prefixed units in the result. Default is `False`.

    Returns:
      units `python:list` of `UnitBase`

        A list of unit objects that match `u`. A subclass of `list` (`EquivalentUnitsList`) is returned that pretty-prints the list of units when output.

  get_converter(other, equivalencies=[])

    Create a function that converts values from this unit to another.

    Parameters:
      other astropy:unit-like

        The unit to convert to.

      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. This list is in addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies.

    Returns:
      func `python:callable()`

        A callable that takes an array-like argument and returns it converted from units of self to units of other.

    Raises:
      `UnitsError`

        If the units cannot be converted to each other.

    Notes

    This method is used internally in `Quantity` to convert to different units. Note that the function returned takes and returns values, not quantities.

  in_units(other, value=1.0, equivalencies=[])

    Deprecated since version 7.0: The in_units function is deprecated and may be removed in a future version. Use to() instead.

    Alias for `to` for backward compatibility with pynbody.

  is_equivalent(other, equivalencies=[])

    Check whether this unit is equivalent to `other`.

    Parameters:
      other `Unit`, `python:str`, or `python:tuple`

        The unit to convert to. If a tuple of units is specified, this method returns true if the unit matches any of those in the tuple.

      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. This list is in addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies.

    Returns:
      bool
  is_unity()

    Check whether the unit is unscaled and dimensionless.

  to(other, value=1.0, equivalencies=[])

    Return the converted values in the specified unit.

    Parameters:
      other astropy:unit-like

        The unit to convert to.

      value `python:int`, `python:float`, or scalar numpy:array_like, optional

        Value(s) in the current unit to be converted to the specified unit. If not provided, defaults to 1.0

      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. This list is in addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies.

    Returns:
      values scalar or `array`

        Converted value(s). Input value sequences are returned as numpy arrays.

    Raises:
      `UnitsError`

        If units are inconsistent

  to_string(format=None, *, deprecations='warn', **kwargs)

    Output the unit in the given format as a string.

    Parameters:
      format `astropy.units.format.Base` subclass or `python:str` or `python:None`

        The name of a format or a formatter class. If not provided (or `None`), defaults to the generic format.

      deprecations{“warn”, “silent”, “raise”, “convert”}, optional, keyword-only

        Whether deprecated units should emit a warning, be handled silently or raise an error. The “convert” option replaces the deprecated unit if possible and emits a warning otherwise.

      **kwargs

        Further options forwarded to the formatter. Currently recognized is `fraction`, which can take the following values:

        - `False` : display unit bases with negative powers as they are;

        - ‘inline’ or `True` : use a single-line fraction;

        - ‘multiline’ : use a multiline fraction (available for the ‘latex’, ‘console’ and ‘unicode’ formats only; for others, an ‘inline’ fraction is used).

    Raises:
      `TypeError`

        If `format` is of the wrong type.

      `ValueError`

        If `format` or `fraction` are not recognized.

    Examples

        >>> import astropy.units as u
        >>> kms = u.Unit('km / s')
        >>> kms.to_string()  # Generic uses fraction='inline' by default
        'km / s'
        >>> kms.to_string('latex')  # Latex uses fraction='multiline' by default
        '$\\mathrm{\\frac{km}{s}}$'
        >>> print(kms.to_string('unicode', fraction=False))
        km s⁻¹
        >>> print(kms.to_string('unicode', fraction='inline'))
        km / s
        >>> print(kms.to_string('unicode', fraction='multiline'))
        km
        ──
        s

  to_system(system)

    Convert this unit into ones belonging to the given system.

    Since more than one result may be possible, a list is always returned.

    Parameters:
      system python:module

        The module that defines the unit system. Commonly used ones include `astropy.units.si` and `astropy.units.cgs`.

        To use your own module it must contain unit objects and a sequence member named `bases` containing the base units of the system.

    Returns:
      units `python:list` of `CompositeUnit`

        With an attempt to sort simpler units to the start (see examples).

    Examples

        >>> import astropy.units as u
        >>> (u.N / u.m**2).to_system(u.si)  # preference for simpler units
        [Unit("Pa"), Unit("N / m2"), Unit("J / m3")]
        >>> u.Pa.to_system(u.cgs)
        [Unit("10 Ba"), Unit("10 P / s")]
        >>> u.Ba.to_system(u.si)
        [Unit("0.1 Pa"), Unit("0.1 N / m2"), Unit("0.1 J / m3")]
        >>> (u.AU/u.yr).to_system(u.cgs)  # preference for base units
        [Unit("474047 cm / s"), Unit("474047 Gal s")]
        >>> (u.m / u.s**2).to_system(u.cgs)
        [Unit("100 cm / s2"), Unit("100 Gal")]