Serialization#

Serialization of Unit and Quantity objects.

Supported formats:

  • Plain dictionaries: Quantity.to_dict() and Quantity.from_dict() (and the Unit equivalents). This is also the format used by the pydantic integration, which provides JSON support (model_dump_json, TypeAdapter(Quantity).dump_json). Without pydantic, use json.dumps(quantity.to_dict()) and Quantity.from_dict(json.loads(text)).

  • Strings: Quantity.from_string() parses the output of str(quantity).

  • Pickle: units are pickled by name and resolved again when unpickled.

Units are always stored by name. When loading, a name is resolved against an explicitly given UnitRegistry, then against the application registry (see set_application_registry()), and finally against the built-in units. Custom units that are only known to a registry are stored together with their definition so that they can be restored even when no registry defines them.

ansys.units.serialization.set_application_registry(registry: UnitRegistry | None) → None#

Set the registry used to resolve unit names when loading serialized data.

The application registry is used by unpickling and by any loading function called without an explicit registry. This allows custom units registered with register_unit() to be restored by name.

Parameters:
registryUnitRegistry or None

Registry to use, or None to use only the built-in units.

Examples

>>> import pickle
>>> from ansys.units import UnitRegistry, set_application_registry
>>> ur = UnitRegistry()
>>> micron = ur.register_unit(unit="micron", composition="m", factor=1e-6)
>>> set_application_registry(ur)
>>> q = pickle.loads(pickle.dumps(ur.Quantity(3, "micron")))
>>> q.units == ur.micron
True
ansys.units.serialization.get_application_registry() → UnitRegistry | None#

Return the registry set with set_application_registry(), if any.

ansys.units.serialization.resolve_unit(name: str, definition: Mapping[str, Any] | None = None, registry: UnitRegistry | None = None) → Unit#

Resolve a unit name for deserialization.

Parameters:
namestr

Unit name.

definitiondict, optional

Definition with composition (SI unit string) and factor (SI scaling factor), used when the name cannot be resolved otherwise.

registryUnitRegistry, optional

Registry to resolve the name against. Defaults to the application registry.

Returns:
Unit

The resolved unit.

Raises:
UnresolvableUnit

If the name cannot be resolved and no definition is given.

ConflictingUnitDefinition

If the resolved unit does not match the given definition.

exception ansys.units.serialization.UnresolvableUnit(name: str)#

Bases: ValueError

Raised when a serialized unit name cannot be resolved.

exception ansys.units.serialization.ConflictingUnitDefinition(name: str)#

Bases: ValueError

Raised when a serialized unit definition differs from the registry’s unit.