Note
Go to the end to download the full example code.
Unit aliases#
PyAnsys Units supports unit aliases so you can use shorthand or
alternative names for units. For example, deg for degree or
meter for m.
This example shows you how to:
Use built-in aliases in unit and quantity creation.
Use aliases inside compound unit strings.
Register custom aliases programmatically.
Perform conversions with aliased units.
Perform required imports#
from ansys.units import Quantity, Unit, UnitRegistry
Built-in aliases#
Several common aliases are shipped out of the box. Use deg instead
of degree, rad instead of radian, meter instead of m,
and so on.
angle = Unit("deg")
print(f"Unit('deg') -> name={angle.name!r}, sf={angle.si_scaling_factor}")
length = Unit("meter")
print(f"Unit('meter') -> name={length.name!r}")
force = Unit("newton")
print(f"Unit('newton') -> name={force.name!r}")
Unit('deg') -> name='degree', sf=0.017453292519943295
Unit('meter') -> name='m'
Unit('newton') -> name='N'
Aliases in quantities#
Aliases work seamlessly when creating Quantity objects.
Quantity(90, 'deg') = 90.0 degree
Quantity(5.0, 'meter') = 5.0 m
Aliases in compound units#
Aliases can be mixed with canonical names inside compound unit strings.
angular_velocity = Unit("deg sec^-1")
print(f"Unit('deg sec^-1') -> name={angular_velocity.name!r}")
acceleration = Unit("meter sec^-2")
print(f"Unit('meter sec^-2') -> name={acceleration.name!r}")
Unit('deg sec^-1') -> name='degree s^-1'
Unit('meter sec^-2') -> name='m s^-2'
Conversions with aliases#
Unit conversions work normally when aliases are used.
180 deg = 3.141593 radian
1 meter = 3.280840 ft
Register a custom alias#
You can register your own aliases at runtime via UnitRegistry.
ureg = UnitRegistry()
ureg.register_alias("angular_deg", "degree")
custom = Unit("angular_deg")
print(f"Unit('angular_deg') -> name={custom.name!r}")
Unit('angular_deg') -> name='degree'
Alias equality#
A unit created from an alias is fully equal to the canonical unit.
assert Unit("deg") == Unit("degree")
assert Unit("rad") == Unit("radian")
assert Unit("meter") == Unit("m")
print("All alias-based units equal their canonical counterparts.")
All alias-based units equal their canonical counterparts.
Total running time of the script: (0 minutes 0.021 seconds)