ubii.framework.util.enum module

class ubii.framework.util.enum.EnumMatcher

Bases: object

Used to compare tuples of IntFlag enums. Tuples are considered ‘matching’ if all flags from the query enums are also set in the base enum.

Example

Consider the enum

>>> import enum
>>> class Flags(enum.IntFlag):
...     ONE = enum.auto()
...     TWO = enum.auto()
...     COMBINED = ONE | TWO

Because how IntFlag enums work, we now have Flags.ONE == int(b'01') == 1 and Flags.TWO == int(b'10') == 2 and Flags.COMBINED == int(b'11') == 3. Since all flags in the COMBINED value are set, we have

>>> from ubii.framework.util import EnumMatcher
>>> EnumMatcher.flags_match(base=Flags.ONE, query=Flags.COMBINED)
True
>>> EnumMatcher.flags_match(base=Flags.COMBINED, query=Flags.ONE)
False

And for tuples of values

>>> values = (Flags.ONE, Flags.ONE, Flags.TWO, Flags.COMBINED)
>>> EnumMatcher.matches(base=values, query=tuple([Flags.COMBINED] * len(values)))
True

If we have a mapping of IntFlag tuples to some values, we can extract values for ‘matching’ keys:

>>> mapping = {
...     (Flags.ONE, Flags.TWO): "Foo",
...     (Flags.TWO, Flags.COMBINED): "Bar"
... }
>>> EnumMatcher.get_matching_value(query=(Flags.COMBINED, Flags.COMBINED), mapping=mapping)
["Foo", "Bar"]
classmethod flags_match(base: T_EnumFlag, query: T_EnumFlag)

Compute if all flags set in base are also set in query by computing base & query == query

classmethod matches(base: Sequence[T_EnumFlag], query: Sequence[T_EnumFlag]) bool
Parameters:
  • base – a tuple of flag enums that need to be matched

  • query – a tuple of flag enums

Returns:

True if flags_match() is True at every position of the tuples. False otherwise or if tuples have different length or if they contain None values.

classmethod get_matching_value(query: Sequence[T_EnumFlag], default: Any = _no_default, *, mapping: Mapping[Sequence[T_EnumFlag], T]) T
Parameters:
  • query – tuple used as query for matches()

  • default – default value if no matches are found – optional

  • mapping – Mapping \((IntFlag, IntFlag, ...) \rightarrow Value\), keys are considered base values for matches()

Returns:

All values from mapping where EnumMatcher.matches(key, query) is True, otherwise default if set.

Raises:

KeyError – if no matches for query found in mapping and no default is given