In a word: Yes1.
I will show a solution using the aenum
2 library -- while it is possible to do most of this with the stdlib version it would require writing extra plumbing that already exists in aenum
.
First, the base class:
from aenum import Enum, enum
class CallableEnum(Enum):
def __new__(cls, *args, **kwds):
member = object.__new__(cls)
member._impl = args[0]
if member._impl.__doc__ is not None:
member._value_ = member._impl.__doc__
else:
member._value_ = repr(member._impl)
return member
def __call__(self, *args, **kwds):
return self._impl(*args, **kwds)
and an example dispatch Enum
:
class TestEnum(CallableEnum):
@enum
def hello(text):
"a pleasant greeting"
print('hello,', text)
@enum
def goodbye(text):
print('goodbye,', text)
and in use:
>>> list(TestEnum)
[
<TestEnum.hello: 'a pleasant greeting'>,
<TestEnum.goodbye: '<function goodbye at 0xb7264844>'>,
]
>>> print(TestEnum.hello)
TestEnum.hello
>>> TestEnum['hello']('how are you?')
'hello, how are you?'
>>> TestEnum['goodbye']('see you soon!')
'goodbye, see you soon!'
1 See this answer for the standard Enum
usage.
2 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.