Unit registry#

class ansys.units.unit_registry.UnitRegistry(config: str = 'cfg.yaml', other: Mapping[str, Mapping[str, Any]] = {}, custom_units: Sequence[Mapping[str, Any]] | None = None, custom_units_file: str | None = None)#

Bases: object

A representation of valid Unit instances.

All base and derived units loaded from the configuration file, cfg.yaml, on package initialization are provided by default.

Parameters:
config: str, optional

Path of a YAML configuration file, which can be a custom file, and defaults to the provided file, cfg.yaml. Custom configuration files must match the format of the default configuration file.

other: dict, optional

Dictionary for additional units (uses config file format).

custom_unitslist of dict, optional

List of custom units to register during construction. Each dict must have keys "unit", "composition", and "factor" matching the register_unit() signature. An optional "aliases" key (a list of strings) is also supported.

custom_units_filestr, optional

Path to a YAML file previously produced by export_custom_units(). Entries are loaded and registered the same way as custom_units, and the two can be combined.

Examples

>>> from ansys.units import UnitRegistry, Unit
>>> ureg = UnitRegistry()
>>> assert ureg.kg == Unit(units="kg")
>>> fps = Unit("ft s^-1")
>>> ureg.foot_per_sec = fps

Register custom units at construction:

>>> ur = UnitRegistry(custom_units=[
...     {"unit": "micron", "composition": "m", "factor": 1e-6},
...     {"unit": "inch", "composition": "m", "factor": 0.0254},
...     {"unit": "furlong", "composition": "m", "factor": 201.168,
...      "aliases": ["furlongs"]},
... ])
>>> q = ur.Quantity(10, "micron")
Quantity(value: float | _ArrayInput, units: str | Unit) → Quantity#

Create a Quantity using this registry’s units.

This method allows creating quantities with instance-registered units using string names.

Parameters:
valueint, float, or sequence

The numeric value.

unitsstr or Unit

The unit name (looked up in this registry) or a Unit object.

Returns:
Quantity

The created quantity.

Examples

>>> ur = UnitRegistry()
>>> ur.register_unit(unit="micron", composition="m", factor=1e-6)
>>> q = ur.Quantity(1, "micron")
>>> print(q)
1.0 micron
export_custom_units(path: str, *, overwrite: bool = False) → None#

Export this registry’s runtime-registered custom units to a YAML file.

Only units registered via register_unit() (directly, or through the custom_units/custom_units_file constructor parameters) are exported. Built-in units are never included. The resulting file can be reloaded with load_custom_units() or passed directly as custom_units_file to a new UnitRegistry.

Parameters:
pathstr

Destination file path.

overwritebool, optional

Whether to overwrite path if it already exists. Default is False.

Raises:
ValueError

If this registry has no custom registered units to export.

FileExistsError

If path already exists and overwrite is False.

Examples

>>> from ansys.units.common import m
>>> ur = UnitRegistry()
>>> ur.register_unit("furlong", 201.168 * m, aliases=["furlongs"])
>>> ur.export_custom_units("units.yaml")
>>> ur2 = UnitRegistry(custom_units_file="units.yaml")
>>> ur2.furlong is ur2.furlongs
True
get_unit(name: str) → Unit#

Look up a unit by name from this registry.

Checks instance-registered units first, then falls back to built-in units and compound unit strings. This allows string-based lookup of custom registered units as well as standard unit expressions.

Parameters:
namestr

The unit name or compound unit string to look up (e.g., “micron”, “m”, “kg mol^-1”).

Returns:
Unit

The unit object.

Raises:
AttributeError

If the unit is not found in this registry or cannot be parsed.

register_alias(alias: str, canonical: str) → None#

Register a new alias for an existing unit.

The alias is added to the global alias table so that it can be used anywhere a unit string is accepted (Unit(), Quantity(), etc.).

Parameters:
aliasstr

The alias name (e.g., "deg").

canonicalstr

The canonical unit name the alias resolves to (e.g., "degree"). Must be a configured base or derived unit, or an existing alias.

Raises:
AliasAlreadyRegistered

If alias is already registered as a unit or alias.

ValueError

If canonical is not a known unit or alias.

register_unit(unit: str, definition: Unit | Quantity[Any], *, aliases: Sequence[str] | None = None) → Unit#
register_unit(*, unit: str, composition: str, factor: float, aliases: Sequence[str] | None = None) → Unit

Register a new derived unit on this UnitRegistry instance.

This is instance-scoped: it affects only this registry and does not mutate global state or other registries. The registered unit can be accessed as an attribute (e.g., ur.micron) or via get_unit() for string-based lookup.

This method supports two equivalent calling conventions: an object-based form that accepts a Unit or Quantity definition, and a composition/factor form.

Parameters:
unit: str

The symbol/name of the new unit (e.g., “micron”).

definition: Unit or Quantity, optional

An object-based definition of the new unit, for example 201.168 * m (a Quantity) or a bare Unit instance (treated as a factor of 1). Mutually exclusive with composition/factor.

composition: str, optional

A valid unit composition using existing configured units (e.g., “m”). Must be provided together with factor. Mutually exclusive with definition.

factor: float, optional

Scale factor that relates the composition to this unit. Must be provided together with composition. Mutually exclusive with definition.

aliases: sequence of str, optional

Additional names that resolve to the same registered unit on this instance (e.g., ["furlongs"]).

Returns:
Unit

The registered unit attached on this instance.

Raises:
UnitNameAlreadyRegistered

If unit (or one of aliases) is a built-in unit name, or already exists on this instance with a different effective definition (dimensions, SI scaling factor, or SI offset). Re-registering the same name with an equivalent definition is a no-op that returns the existing unit.

ValueError

If unit or an alias is empty, factor is not finite, or both/neither of definition and composition/factor are given.

Notes

The duplicate-name check compares effective definitions (dimensions, SI scaling factor, and SI offset). Re-registering the same name with an equivalent definition is idempotent. Built-in unit names can never be overridden, even with an equivalent definition. The check does not detect equivalent definitions registered under a different name.

Examples

>>> ur = UnitRegistry()
>>> ur.register_unit(unit="micron", composition="m", factor=1e-6)
>>> q = ur.Quantity(1, "micron")  # Use registry's Quantity method

Object-based form, with an alias:

>>> from ansys.units.common import m
>>> ur.register_unit("furlong", 201.168 * m, aliases=["furlongs"])
>>> ur.furlong == ur.furlongs
True
ansys.units.unit_registry.load_custom_units(path: str) → list[dict[str, Any]]#

Load custom unit definitions from a file written by export_custom_units.

Parameters:
pathstr

Path to a YAML file previously produced by UnitRegistry.export_custom_units().

Returns:
list of dict

A list of custom unit definitions, suitable for passing directly as the custom_units constructor parameter of UnitRegistry.

Examples

>>> ur.export_custom_units("units.yaml")
>>> custom_units = load_custom_units("units.yaml")
>>> ur2 = UnitRegistry(custom_units=custom_units)
exception ansys.units.unit_registry.UnitNameAlreadyRegistered(name: str)#

Bases: ValueError

Raised when a unit name conflicts with an existing name.

This is raised when unit (or an alias) is a built-in unit name, or when it is already registered on the instance with a different effective definition (dimensions, SI scaling factor, or SI offset). Re-registering the same name with an equivalent definition is a no-op and does not raise. Units with different names but equivalent definitions (same composition and factor) are also not detected as conflicts.

exception ansys.units.unit_registry.AliasAlreadyRegistered(name: str)#

Bases: ValueError

Raised when an alias conflicts with an existing unit or alias.