Re: [Python-Dev] Data descriptor doc/implementation inconsistency
Date: Mon, 11 Jan 2010 01:51:09 +0100 From: "Amaury Forgeot d'Arc"
To: Benjamin Peterson Cc: Python Dev Subject: Re: [Python-Dev] Data descriptor doc/implementation inconsistency Message-ID: Content-Type: text/plain; charset=ISO-8859-1 Hi,
2010/1/11 Benjamin Peterson
: Consider this program:
class Descr(object): ? ?def __init__(self, name): ? ? ? ?self.name = name ? ?def __set__(self, instance, what): ? ? ? ?instance.__dict__[self.name] = what
class X(object): ? ?attr = Descr("attr")
x = X() print(x.attr) x.attr = 42 print(x.attr)
It gives in output:
<__main__.Descr object at 0x7fe1c9b28150> 42
The documentation [1] says that Descr is a data descriptor because it defines the __set__ method. It also states that data descriptors always override the value in the instance dictionary. So, the second line should also be the descriptor object according to the documentation.
My question is: Is this a doc bug or a implementation bug? If the former, it will be the description of a data descriptor much less consistent, since it will require that a __get__ method be present, too. If the latter, the fix may break some programs relying on the ability to "cache" a value in the instance dictionary.
[1] http://docs.python.org/reference/datamodel#invoking-descriptors
Quoting the documentation: """Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method. """ Your example is neither a data descriptor nor a non-data descriptor... Actually, there is this footnote [1]:
""" A descriptor can define any combination of __get__(), __set__() and __delete__(). If it does not define __get__(), then accessing the attribute even on an instance will return the descriptor object itself. If the descriptor defines __set__() and/or __delete__(), it is a data descriptor; if it defines neither, it is a non-data descriptor. """ Which would mean Descr is actually a data descriptor without a __get__(), so x.attr should always return the descriptor object itself (at least in the docs).
The thing that worries me a bit is the "x.attr" returning the Descr object. Descriptors should remain at the class level, and instance should only see values. I'd prefer an AttributeError in this case.
-- Amaury Forgeot d'Arc
[1] http://docs.python.org/reference/datamodel#id7 -- Lukasz Rekucki
participants (1)
-
Łukasz Rekucki