ubii.framework.util.enum module¶
- class ubii.framework.util.enum.EnumMatcher¶
Bases:
objectUsed to compare tuples of
IntFlagenums. 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
IntFlagenums work, we now haveFlags.ONE == int(b'01') == 1andFlags.TWO == int(b'10') == 2andFlags.COMBINED == int(b'11') == 3. Since all flags in theCOMBINEDvalue 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
IntFlagtuples 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:
Trueifflags_match()isTrueat every position of the tuples.Falseotherwise or if tuples have different length or if they containNonevalues.
- classmethod get_matching_value(query: Sequence[T_EnumFlag], default: Any = _no_default, *, mapping: Mapping[Sequence[T_EnumFlag], T]) T¶
- Parameters:
- Returns:
All values from
mappingwhereEnumMatcher.matches(key, query)isTrue, otherwisedefaultif set.- Raises:
KeyError – if no matches for
queryfound inmappingand nodefaultis given