[issue1615] descriptor protocol bug

Ethan Furman report at bugs.python.org
Tue Sep 17 16:28:10 CEST 2013


Ethan Furman added the comment:

Benjamin Peterson added the comment:
>
> I consider this to be a feature. Properties can raise AttributeError to defer to
> __getattr__.

Micah Friesen added the comment:
>
>I submit that this is not a feature - I can't imagine a real-world scenario [...]

No need to imagine.  The new Enum class uses this ability to support having both protected properties on enum members and enum members of the same name:

--> from enum import Enum
--> class Field(Enum):
-->     name = 1
...     age = 2
...     location = 3
... 
--> Field.name
<Field.name: 1>
--> Field.name.name
'name'

Enum's custom __getattr__ is located in the metaclass, however, not in the class.  For future reference, here is a short test script and it's output in 3.4.0a2+:
=====================================================================================
class WithOut:
    @property
    def huh(self):
        return self.not_here

class With:
    @property
    def huh(self):
        return self.not_here
    def __getattr__(self, name):
        print('looking up %s' % name)
        raise AttributeError('%s not in class %s' % (name, type(self)))

try:
    WithOut().huh
except AttributeError as exc:
    print(exc)

print()
try:
    With().huh
except AttributeError as exc:
    print(exc)

print()
import enum  # broken value property tries to access self.not_here
class TestEnum(enum.Enum):
    one = 1

print(TestEnum.one.value)
=====================================================================================
'WithOut' object has no attribute 'not_here'

looking up not_here
looking up huh
huh not in class <class '__main__.With'>

meta getattr with __new_member__
meta getattr with __new_member__
meta getattr with one
'TestEnum' object has no attribute 'not_here'
=====================================================================================

----------

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


More information about the Python-bugs-list mailing list