[issue18989] reuse of enum names in class creation inconsistent

Nick Coghlan report at bugs.python.org
Sat Sep 14 18:17:37 CEST 2013


Nick Coghlan added the comment:

OK, rechecking PEP 435, I see that disallowing reuse of a name was indeed explicitly accepted as part of the defined API: http://www.python.org/dev/peps/pep-0435/#duplicating-enum-members-and-values

In that case, I switch my perspective to agree with Ethan that overwriting it with a method or descriptor should *also* be disallowed. The PEP is currently silent on that question, and as Ethan notes in the original post, the weird middle ground of the current behaviour is thoroughly confusing:

>>> class Disallowed(Enum):
...     a = 1
...     a = 2
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in Disallowed
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 87, in __setitem__
    raise TypeError('Attempted to reuse key: %r' % key)
TypeError: Attempted to reuse key: 'a'


>>> class Allowed(Enum):
...     a = 1
...     @property
...     def a(self):
...         return 2
... 
>>> Allowed.a
<property object at 0x7f3d65da14d8>
>>> Allowed().a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __call__() missing 1 required positional argument: 'value'
>>> Allowed(1).a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 218, in __call__
    return cls.__new__(cls, value)
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 439, in __new__
    raise ValueError("%s is not a valid %s" % (value, cls.__name__))
ValueError: 1 is not a valid Allowed
>>> Allowed('a').a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 218, in __call__
    return cls.__new__(cls, value)
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 439, in __new__
    raise ValueError("%s is not a valid %s" % (value, cls.__name__))
ValueError: a is not a valid Allowed
>>> Allowed['a'].a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ncoghlan/devel/py3k/Lib/enum.py", line 255, in __getitem__
    return cls._member_map_[name]
KeyError: 'a'

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18989>
_______________________________________


More information about the Python-bugs-list mailing list