Yassine Faris
Yassine Faris

Reputation: 991

Enum KeyError Function

I am trying to access an function stored inside an Enum using it's name but I get a KeyError:

from enum import Enum

def f():
    pass

class MyEnum(Enum):
   function = f

print MyEnum.function  # <unbound method MyEnum.f>
print MyEnum['function']  # KeyError: 'function'

But it work if the Enum don't store func:

from enum import Enum

class MyEnum(Enum):
   a = "toto"

print MyEnum.a  # MyEnum.a
print MyEnum.a.value  # "toto"
print MyEnum['a']  # MyEnum.a
print MyEnum.a.value  # "toto"

I know I could use dict instead of Enum, but I want to know why Enum behave differently.

Upvotes: 2

Views: 7434

Answers (1)

Giacomo Alzetta
Giacomo Alzetta

Reputation: 2479

Assigning a function is the same as defining it. And if you define a function in an Enum it becomes a method of the Enum and is not taken as a value for enum.

The following enums A and B are completely equivalent:

>>> from enum import Enum
>>> 
>>> class A(Enum):
...     a = 1
...     def f(self):
...         print('Hello')
... 
>>> def x(self):
...     print('Hello')
... 
>>> class B(Enum):
...     a = 1
...     f = x
... 
>>> B.f
<unbound method B.x>
>>> A.f
<unbound method A.f>
>>> A['a']
<A.a: 1>
>>> A['f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 384, in __getitem__
    return cls._member_map_[name]
KeyError: 'f'
>>> B['a']
<B.a: 1>
>>> B['f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 384, in __getitem__
    return cls._member_map_[name]
KeyError: 'f'

Functions are treated differently because otherwise it would impossible to define custom methods in an enum.

Upvotes: 4

Related Questions