Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Rewriting __getattr__

Reply
Thread Tools

Rewriting __getattr__

 
 
kost BebiX
Guest
Posts: n/a
 
      01-06-2011
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>
copy.deepcopy(a)
File "/usr/lib/python2.6/copy.py", line 171, in deepcopy
copier = getattr(x, "__deepcopy__", None)
File "<pyshell#17>", line 5, in __getattr__
self.d[key]
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
self.d[key]

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()
deepcopy(a)

gets "maximum recursion depth exceeded"?

Thank you.

--
jabber: http://www.velocityreviews.com/forums/(E-Mail Removed)
 
Reply With Quote
 
 
 
Reply

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



Advertisments