scipp.units.UnitAliases#

class scipp.units.UnitAliases#

Manager for unit aliases.

Aliases override how units are converted to and from strings. The table is similar to a dict and maps alias names to units. But unlike a dict, no guarantees are made about the order of aliases or their priority in string formatting. And there may be only one alias for each unit at a time.

Attention

This class is a singleton and should never be instantiated by user code. Instead, use it through scipp.units.aliases.

__init__()#

Methods

__init__()

clear()

Remove all aliases.

items()

Iterator over pairs of alias names and units.

keys()

Iterator over alias names.

scoped(**kwargs)

Contextmanager to define temporary aliases.

values()

Iterator over aliased units.

clear()#

Remove all aliases.

items()#

Iterator over pairs of alias names and units.

Return type

Iterable[Tuple[str, Unit]]

keys()#

Iterator over alias names.

Return type

Iterable[str]

scoped(**kwargs)#

Contextmanager to define temporary aliases.

Defines new aliases based on kwargs for the duration of the context. When exiting the context, all temporary aliases are removed.

It is possible to define additional aliases in the context. They are not removed when the context manager exits unless they override scoped aliases. (See examples.)

Warning

This context manager is not thread-safe. Aliases defined here affect all threads and other threads can define different aliases which affect the managed context.

Parameters

**kwargs – Map from names to units for aliases to define.

Examples

Define temporary aliases:

>>> with sc.units.aliases.scoped(speed='m/s'):
...     str(sc.Unit('m/s'))
'speed'

Previously defined aliases still apply:

>>> sc.units.aliases.clear()
>>> sc.units.aliases['dogyear'] = '4492800s'
>>> with sc.units.aliases.scoped(speed='m/s'):
...     str(sc.Unit('4492800s'))
'dogyear'

Previous aliases can be overridden and are restored after the context:

>>> sc.units.aliases.clear()
>>> sc.units.aliases['speed'] = 'km/s'
>>> with sc.units.aliases.scoped(speed='m/s'):
...     sc.Unit('speed') == 'm/s'
True
>>> sc.Unit('speed') == 'km/s'
True

Aliases defined within the context remain active unless they clash with previous alises:

>>> sc.units.aliases.clear()
>>> sc.units.aliases['speed'] = 'km/s'
>>> with sc.units.aliases.scoped(speed='m/s'):
...     sc.units.aliases['speed'] = 'mm/s'
...     sc.units.aliases['dogyear'] = '4492800s'
>>> str(sc.Unit('4492800s'))
'dogyear'
>>> sc.Unit('speed') == 'km/s'
True
values()#

Iterator over aliased units.

Return type

Iterable[Unit]