Rewriting __getattr__

K

kost BebiX

Hi everyone!
I just saw a bug (?) in bson.dbref:DBRef.__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:
... 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top