Since python 3.11, enum
module has a new class decorator enum.global_enum
that puts enum member names in global namespace, and also modifies there repr
such that it appears as if it was defined in global scope, rather than the class scope. Here's an example:
from enum import global_enum, Enum
import cmath
@global_enum
class GloballyFamousConstant(Enum):
# OF COURSE, IN PRACTICE, MEMBER NAMES SHOULD BE IN UPPERCASE
PI = cmath.pi
E = cmath.e
class UnderAppreciatedConstant(Enum):
TAU = cmath.tau
print(f"Hi! I'm the famous {GloballyFamousConstant.E}!")
print(f"Hi! My name is {UnderAppreciatedConstant.TAU}")
print(f'{"e" in globals() = }')
Prints:
Hi! I'm the famous E!
Hi! My name is UnderAppreciatedConstant.TAU
"E" in globals() = True
Although the repr
of the members show their names, they behave like their mixin parent's value if derived from a mixin under almost all circumstances. They are essentially equal to their value. If needed, the exact underlying value can be queried using the value
attribute, like normal enums.
## # IGNORE: start #
## class Complex:
## def __init__(self, real=0, imag=1):
## self.real, self.imag = real, imag
##
## def __rpow__(self, other, /):
## val = other ** complex(self.real, self.imag)
## return Complex(val.real, val.imag)
##
## def __mul__(self, other, /):
## val = complex(self.real, self.imag) ** other
## return int(val.real)
##
##
## i = Complex(real=0, imag=1)
## # IGNORE: end #
from enum import global_enum, Enum
import cmath
@global_enum
class GloballyFamousConstant(float, Enum):
# OF COURSE, IN PRACTICE, MEMBER NAMES SHOULD BE IN UPPERCASE
π = cmath.pi
e = cmath.e
print(f"{e ** i*π + 1 = }")
print(f"Where {e}={e.value}, {π}={π.value}")
# prints:
# e ** i*π + 1 = 0
# Where e=2.718281828459045, π=3.141592653589793
NOTE:
At the time of writing this (23rd Jul, 2024), no type checkers/linters support this feature as per my knowledge.