473,320 Members | 2,189 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

py2.1->py2.3.3 __getattr__ confusion

Hi there,
please excuse my rather lengthy post.
With introduction of the new style classes, something
seems to have changed for __getattr__ hooks, even
for classic classes:

getattr.py:
class A: # classic!
def __getattr__(self, attr):
print "-->A.__getattr__"
print "attr=", attr
print "<--A.__getattr__"
return self.__dict__[attr]

a = A()
print "a.__dict__:", a.__dict__
a.foo()
x = a.foo
print "a.foo:", a.foo

$ python2.1 getattr2.py
a.__dict__: {}
A.foo()
a.foo: <method A.foo of A instance at c37d0>

$ python2.3 getattr2.py
a.__dict__: {}
A.foo()
a.foo: -->A.__getattr__
attr= __repr__
<--A.__getattr__
Traceback (most recent call last):
File "getattr2.py", line 22, in ?
print "a.foo:", a.foo
File "getattr2.py", line 6, in __getattr__
return self.__dict__[attr]
KeyError: '__repr__'

I didn´t find the explanation for this behaviour in the
"what´s new" sections and the docs (and googling).
Probably I missed it - any hints?

Formerly, the instance attribute lookup mechanism was:
1. local __dict__
2. corresponding class definition
3. __getattr__

Now, this seems to work different for the a.foo lookup,
but not for the a.foo() method invocation?!

If I change my class A __getattr__ method in the following way,
I seem to workaround the problem:

class A:
def __getattr__(self, attr):
print "-->A.__getattr__"
print "attr=", attr
print "<--A.__getattr__"
return self.__dict__[attr]
# Use this Try-except-raise AttributeError to get the same
behaviour
# in python 2.2+ as in python 1.5.2
# try:
# return self.__dict__[attr]
# except KeyError:
# raise AttributeError

Is this a valid workaround to apply to old __getattr__ hooks?

Thanks for any hints,
Holger

Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene
Empfänger sind oder falls diese E-Mail irrtümlich an Sie adressiert wurde,
verständigen Sie bitte den Absender sofort und löschen Sie die E-Mail
sodann. Das unerlaubte Kopieren sowie die unbefugte Übermittlung sind nicht
gestattet. Die Sicherheit von Übermittlungen per E-Mail kann nicht
garantiert werden. Falls Sie eine Bestätigung wünschen, fordern Sie bitte
den Inhalt der E-Mail als Hardcopy an.

The contents of this e-mail are confidential. If you are not the named
addressee or if this transmission has been addressed to you in error,
please notify the sender immediately and then delete this e-mail. Any
unauthorized copying and transmission is forbidden. E-Mail transmission
cannot be guaranteed to be secure. If verification is required, please
request a hard copy version.

Jul 18 '05 #1
1 1370
Holger Joukl wrote:
With introduction of the new style classes, something
seems to have changed for __getattr__ hooks, even
for classic classes:


Here is what I think it boils down to:

<joukl_getattr.py>
class A:
def __getattr__(self, name):
raise Exception

repr(A())
</joukl_getattr.py>

$ python2.1 joukl_getattr.py
$ python2.2 joukl_getattr.py
$ python2.3 joukl_getattr.py
Traceback (most recent call last):
File "joukl_getattr.py", line 20, in ?
repr(A())
File "joukl_getattr.py", line 18, in __getattr__
raise Exception
Exception

<joukl_getattr2.py>
class A:
def __getattr__(self, name):
print name
raise AttributeError

repr(A())
</joukl_getattr2.py>

$ python2.2 joukl_getattr2.py
__repr__
$ python2.3 joukl_getattr2.py
__repr__

That is, starting with Python 2.3 the repr() and str() functions no longer
mask exceptions other than AttributeError. Solution: make sure you raise an
AttributeError instead of the current KeyError for nonexistent attributes.
Peter

Jul 18 '05 #2

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

Similar topics

3
by: Greg Brunet | last post by:
In adding the ability to refer to field values using dbfFile.field notation, I learned how to use __getattr__ and __setattr__ . After some trial and error, I got it working. But as part of my...
3
by: Chris Curvey | last post by:
Hi all, I have this program class Company: def __init__(self, revenues, costs): self.revenues = revenues self.costs = costs def __getattr__(self, name):
0
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called...
13
by: Pelmen | last post by:
How can I get rid of recursive call __getattr__ inside this method, if i need to use method or property of the class?
6
by: Erik Johnson | last post by:
Maybe I just don't know the right special function, but what I am wanting to do is write something akin to a __getattr__ function so that when you try to call an object method that doesn't exist,...
5
by: glomde | last post by:
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some...
2
by: Peter Bengtsson | last post by:
Hi, I'm trying to pickle an object instance of a class that is like a dict but with a __getattr__ and I'm getting pickling errors. This works but is not good enough. $ python2.4 .... pass...
7
by: Roc Zhou | last post by:
Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def...
4
by: Enrico | last post by:
Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise...
7
by: =?UTF-8?Q?Alexandru_Mo=C8=99oi?= | last post by:
i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.