Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Rewriting __getattr__

Thread Tools

Rewriting __getattr__

kost BebiX
Posts: n/a
Hi everyone!
I just saw a bug (?) in bson.dbrefBRef.__getattr__

Here's they're code:
ššš def __getattr__(self, key):
ššššššš return self.__kwargs[key]

And when you do copy.deepcopy on that object it will raise you KeyError. So here's a small piece of code that reproduces the problem:

>>> class A(object):

... def __init__(self):
... self.d = {}
... def __getattr__(self, key):
... self.d[key]
... a = A()
... copy.deepcopy(a)
Traceback (most recent call last):
File "<pyshell#17>", line 7, in <module>
File "/usr/lib/python2.6/", line 171, in deepcopy
copier = getattr(x, "__deepcopy__", None)
File "<pyshell#17>", line 5, in __getattr__
KeyError: '__deepcopy__'

So I thought the right thing right now will be to do just:

class A(object):
def __init__(self):
self.d = {}
def __getattr__(self, key):
if key.startswith('__'):
raise AttributeError

and it works, but... isn't that wrong? I mean, shouldn't deepcopy somehow work in this situation, or, maybe, something else should differ? And why this code:

class A(object):
def __init__(self):
self.d = {}
def __getattr__(self, key):
if key in dir(self.d):
return self.d[key]
raise AttributeError
a = A()

gets "maximum recursion depth exceeded"?

Thank you.

jabber: Removed)
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Rewriting __getattr__ kost BebiX Python 4 01-08-2011 02:13 AM
py2.1->py2.3.3 __getattr__ confusion Holger Joukl Python 1 07-02-2004 02:00 PM
Operator overloading and __getattr__ Samuel Kleiner Python 6 01-13-2004 06:39 AM
__setattr__ and __getattr__ with derived classes Anand Python 0 12-18-2003 09:36 PM
__getattr__ weirdness Greg Brunet Python 3 08-22-2003 08:29 PM