In case of handling multiple Enum/IntEnum or IntFlag, to adjoin and create a new Enum, a simple work around using Stackoverflow answer.
from enum import Enum, IntFlag
def extend_flag(inherited,_type):
def wrapper(final):
joined = {}
inherited.append(final)
for i in inherited:
for j in i:
joined[j.name] = j.value
return _type(final.__name__, joined)
return wrapper
and when using this with Enum, it works just fine with Enum but behaves strangely with other Py versions, but works cool in version 3.9
class A(Enum):
a = "one"
b = "two"
class B(Enum):
c = "three"
d = "four"
@extend_flag([A,B], Enum)
class C(Enum):
e = "five"
print(C('three'))
print(C.b)
print(list(C))
output:
C.c
C.b
[<C.a: 'one'>, C.b: 'two'>, <C.c: 'three'>, <C.d: 'four'>, <C.e: 'five'>]
Update:
with the extend_flag decorator for multiple Enums/Flags,
up on digging more, in version 3.9.6, both Enum and IntFlag works just fine.
from enum import Enum, IntFlag
class A(Enum):
a = "one"
b = "two"
class B(Enum):
c = "three"
d = "four"
class C(IntFlag):
e = 0x05
f = 0x0A4
g = 0x0457C
class D(IntFlag):
h = 0x07
i = 0x0B12
j = 0x04C
@extend_flag([A,B], Enum)
class E(Enum):
h = "five"
@extend_flag([C,D], IntFlag)
class F(IntFlag):
k = 0x09
l = 0x0B2
if __name__ == '__main__':
print(list(E))
print(list(F))
and the output (Python 3.9.6),
[<E.a: 'one'>, <E.b: 'two'>, <E.c: 'three'>, <E.d: 'four'>, <E.h: 'five'>]
[<F.e: 5>, <F.f: 164>, <F.g: 17788>, <F.h: 7>, <F.i: 2834>, <F.j: 76>, <F.k: 9>, <F.l: 178>]
in version 3.12.2, the IntFlag members can be assigned as follows:
class First(IntFlag):
m1 = 0x0001
m2 = 0x0002
m3 = 0x0004
m4 = 0x0008
class Second(IntFlag):
m5 = 0x0010
m6 = 0x0020
m7 = 0x0040
m8 = 0x0080
m9 = 0x0100
class Third(IntFlag):
m10 = 0x200
m11 = 0x400
.
..
(and so on..)
I'm not sure it's the right way to do it. But for me, it just serves the purpose, tho I couldn't figure out a better solution. Enum, IntEnum and IntFlag can also be combined using Union of types or by creating a new type using NewType in latest versions but that's out of scope.
OrderedDict
, you can give just the list comprehension. – Opera