Serialization#
Serialization of Unit and Quantity objects.
Supported formats:
Plain dictionaries:
Quantity.to_dict()andQuantity.from_dict()(and theUnitequivalents). This is also the format used by the pydantic integration, which provides JSON support (model_dump_json,TypeAdapter(Quantity).dump_json). Without pydantic, usejson.dumps(quantity.to_dict())andQuantity.from_dict(json.loads(text)).Strings:
Quantity.from_string()parses the output ofstr(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 withregister_unit()to be restored by name.- Parameters:
- registry
UnitRegistryorNone Registry to use, or
Noneto use only the built-in units.
- registry
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:
- Returns:
UnitThe resolved unit.
- Raises:
UnresolvableUnitIf the name cannot be resolved and no definition is given.
ConflictingUnitDefinitionIf the resolved unit does not match the given definition.
- exception ansys.units.serialization.UnresolvableUnit(name: str)#
Bases:
ValueErrorRaised when a serialized unit name cannot be resolved.
- exception ansys.units.serialization.ConflictingUnitDefinition(name: str)#
Bases:
ValueErrorRaised when a serialized unit definition differs from the registry’s unit.