Rewriting __getattr__

Discussion in 'Python' started by kost BebiX, Jan 6, 2011.

  1. kost BebiX

    kost BebiX Guest

    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:

    >>> 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:
    kost BebiX, Jan 6, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Greg Brunet

    __getattr__ weirdness

    Greg Brunet, Aug 22, 2003, in forum: Python
    Replies:
    3
    Views:
    338
    Greg Brunet
    Aug 22, 2003
  2. Anand
    Replies:
    0
    Views:
    409
    Anand
    Dec 18, 2003
  3. Samuel Kleiner

    Operator overloading and __getattr__

    Samuel Kleiner, Dec 22, 2003, in forum: Python
    Replies:
    6
    Views:
    1,904
    Shalabh Chaturvedi
    Jan 13, 2004
  4. Holger Joukl

    py2.1->py2.3.3 __getattr__ confusion

    Holger Joukl, Jul 2, 2004, in forum: Python
    Replies:
    1
    Views:
    308
    Peter Otten
    Jul 2, 2004
  5. kost BebiX

    Re: Rewriting __getattr__

    kost BebiX, Jan 7, 2011, in forum: Python
    Replies:
    4
    Views:
    557
    kost BebiX
    Jan 8, 2011
Loading...

Share This Page