Let's start with a simple function and put it inside an Enum:
def foo():
return 'foo'
from enum import Enum
class EnumWithFuncs(Enum):
FOO = foo
And we are going to compare it with a "regular" Enum of strings:
class EnumWithStrings(Enum):
FOO = 'foo'
My Python 3.8.9 accepts both of these definitions, but EnumWithFuncs behaves very differently:
# first experiment: does 'FOO' field exist? It does and the function is callable!
>>> EnumWithStrings.FOO
<EnumWithStrings.FOO: 'foo'>
>>> EnumWithFuncs.FOO
<function foo at 0x104b54550>
>>> EnumWithFuncs.FOO()
'foo'
# second experiment: trying to list all elements of the Enum and FOO is gone!
>>> list(EnumWithStrings)
[<EnumWithStrings.FOO: 'foo'>]
>>> list(EnumWithFuncs)
[]
# third experiment: 'FOO' doesn't exist in dir() either
>>> dir(EnumWithStrings)
['FOO', '__class__', '__doc__', '__members__', '__module__']
>>> dir(EnumWithFuncs)
['__class__', '__doc__', '__members__', '__module__']
Can someone explain what's going on here? How can I use functions as values inside an Enum?