472,364 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,364 software developers and data experts.

Inconsistent behavior of descriptors


I've noticed that the order of attribute lookup is inconsistent
when descriptor is used. property instance takes precedence of
instance attributes:
class A(object): .... def _get_attr(self):
.... return self._attr
.... attr = property(_get_attr)
.... a=A()
a.__dict__ {} a.__dict__['attr']=1
a.__dict__ {'attr': 1} a.attr Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in _get_attr
AttributeError: 'A' object has no attribute '_attr'

But it doesn't when I use custom class of descriptor:
class descr(object): .... def __get__(self, inst, cls):
.... return inst._attr
.... class B(object): .... attr = descr()
.... b=B()
b.__dict__ {} b.__dict__['attr']=1
b.__dict__ {'attr': 1} b.attr 1

Subclasses of property behave like property itself:
class descr2(property): .... def __get__(self, inst, cls):
.... return inst._attr
.... class C(object): .... attr = descr2()
.... c=C()
c.__dict__ {} c.__dict__['attr']=1
c.__dict__ {'attr': 1} c.attr

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __get__
AttributeError: 'C' object has no attribute '_attr'

Is it an undocumented feature or I have to submit a bug report?

--
Denis S. Otkidach
http://www.python.ru/ [ru]
Jul 18 '05 #1
2 1829

"Denis S. Otkidach" <od*@strana.ru> wrote in message
news:ma**********************************@python.o rg...

I've noticed that the order of attribute lookup is inconsistent
when descriptor is used. property instance takes precedence of
instance attributes:
class A(object): ... def _get_attr(self):
... return self._attr
... attr = property(_get_attr)
... a=A()
a.__dict__ {} a.__dict__['attr']=1
a.__dict__ {'attr': 1} a.attr Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in _get_attr
AttributeError: 'A' object has no attribute '_attr'

But it doesn't when I use custom class of descriptor:
class descr(object): ... def __get__(self, inst, cls):
... return inst._attr
... class B(object): ... attr = descr()
... b=B()
b.__dict__ {} b.__dict__['attr']=1
b.__dict__ {'attr': 1} b.attr 1

Subclasses of property behave like property itself:
class descr2(property): ... def __get__(self, inst, cls):
... return inst._attr
... class C(object): ... attr = descr2()
... c=C()
c.__dict__ {} c.__dict__['attr']=1
c.__dict__ {'attr': 1} c.attr
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __get__
AttributeError: 'C' object has no attribute '_attr'

Is it an undocumented feature or I have to submit a bug report?


I'm not entirely sure what you're describing, however, I
notice that your descriptor object has a __get__ method,
but no __set__ or __del__ methods. The lookup chain
is quite different for descriptors with only __get__ methods
than it is for descriptors for all three.

In particular, it's intended that instance attributes should
be ignored if there is a data descriptor (that is, a descriptor
with both__get__ and __set__ methods.)

I'm not sure if this applies to your problem.

John Roth
--
Denis S. Otkidach
http://www.python.ru/ [ru]

Jul 18 '05 #2
On Tue, 30 Sep 2003 20:15:10 +0400 (MSD), "Denis S. Otkidach" <od*@strana.ru> wrote:

I've noticed that the order of attribute lookup is inconsistent
when descriptor is used. property instance takes precedence of
instance attributes:
class A(object):... def _get_attr(self):
... return self._attr
... attr = property(_get_attr)
... a=A()
a.__dict__{} a.__dict__['attr']=1
a.__dict__{'attr': 1} a.attrTraceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in _get_attr
AttributeError: 'A' object has no attribute '_attr'

But it doesn't when I use custom class of descriptor:
class descr(object):... def __get__(self, inst, cls):
... return inst._attr
... class B(object):... attr = descr()
... b=B()
b.__dict__{} b.__dict__['attr']=1
b.__dict__{'attr': 1} b.attr1

Subclasses of property behave like property itself:
class descr2(property):... def __get__(self, inst, cls):
... return inst._attr
... class C(object):... attr = descr2()
... c=C()
c.__dict__{} c.__dict__['attr']=1
c.__dict__{'attr': 1} c.attr

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __get__
AttributeError: 'C' object has no attribute '_attr'

Is it an undocumented feature or I have to submit a bug report?

I think (not having read the above carefully) that it's all documented in

http://users.rcn.com/python/download/Descriptor.htm

(thanks to Raymond Hettinger).

excerpt:
"""
The details of invocation depend on whether obj is an object or a class.
Either way, descriptors only work for new style objects and classes. A
class is new style if it is a subclass of object.

For objects, the machinery is in object.__getattribute__ which
transforms b.x into type(b).__dict__['x'].__get__(b, type(b)). The
implementation works through a precedence chain that gives data
descriptors priority over instance variables, instance variables
priority over non-data descriptors, and assigns lowest priority to
__getattr__ if provided. The full C implementation can be found in
PyObject_GenericGetAttr() in Objects/object.c.

For classes, the machinery is in type.__getattribute__ which transforms
B.x into B.__dict__['x'].__get__(None, B). In pure Python, it looks
like:

def __getattribute__(self, key):
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v

The important points to remember are:

descriptors are invoked by the __getattribute__ method
overriding __getattribute__ prevents automatic descriptor calls
__getattribute__ is only available with new style classes and objects
object.__getattribute__ and type.__getattribute__ make different calls to __get__.
data descriptors always override instance dictionaries.
non-data descriptors may be overridden by instance dictionaries.
"""

Regards,
Bengt Richter
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: François Pinard | last post by:
This question is a bit technical, but hopefully, this list will offer me good hints or nice solutions. Happily enough for me, it often does! :-) I would need to recognise and play with...
1
by: bk_kl | last post by:
Hi, I think the following behavior of the build in function 'split' is inconsistent. What do you think? >>> "".split() >>> "".split(";")
14
by: Antoon Pardon | last post by:
Can anyone explain why descriptors only work when they are an attribute to an object or class. I think a lot of interesting things one can do with descriptors would be just as interesting if the...
6
by: Samuel M. Smith | last post by:
I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. The dict class has some read only attributes that generate an exception if I try to...
20
by: Francine.Neary | last post by:
I am learning C, having fun with strings & pointers at the moment! The following program is my solution to an exercise to take an input, strip the first word, and output the rest. It works fine...
9
by: Lie | last post by:
I've noticed some oddly inconsistent behavior with int and float: Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23) on linux2 -345 works, but Traceback (most recent call last): File...
6
by: Kai-Uwe Bux | last post by:
Juha Nieminen wrote: I think your code violates the One-Definition-Rule. The template function foo() is defined in two significantly different ways in the two files. As far as I know, no...
8
by: Michele Petrazzo | last post by:
Hi all, I want to modify the method that set use for see if there is already an object inside its obj-list. Something like this: class foo: pass bar1 = foo() bar1.attr = 1 bar2 = foo()...
2
by: DJ Dharme | last post by:
Hi all, I am writing a multi-threaded application in c++ running on solaris. I have a file which is updated by a single thread by appending data into the file and at same time the other threads...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.