473,791 Members | 3,097 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getattr() woes

Hello

I've found out about a fundamental problem of attribute lookup, the
hard way.

asyncore.py uses the following code:

class dispatcher:
# ...
def __getattr__(sel f, attr):
return getattr(self.so cket, attr)

Now suppose that I'm asking for some attribute not provided by
dispatcher: The lookup mechanism will apparently try to find it
directly and fail, generating an AttributeError; next it will call
__getattr__ to find the attribute. So far, no problems.

But I used a property much like this:
import asyncore
class Peer(asyncore.d ispatcher): .... def _get_foo(self):
.... # caused by a bug, several stack levels deeper
.... raise AttributeError( 'hidden!')
.... foo = property(_get_f oo)
....

and as the error message suggests, the original AttributeError is
hidden by the lookup mechanism:
Peer().foo

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/asyncore.py", line 366, in __getattr__
return getattr(self.so cket, attr)
AttributeError: 'NoneType' object has no attribute 'foo'

Is there anything that can be done about this? If there are no better
solutions, perhaps the documentation for property() could point out
this pitfall?

- Thomas

--
If you want to reply by mail, substitute my first and last name for
'foo' and 'bar', respectively, and remove '.invalid'.
Jul 18 '05 #1
4 1682
In article <87************ @thomas.local>,
Thomas Rast <fo*****@freesu rf.ch.invalid> wrote:

I've found out about a fundamental problem of attribute lookup, the
hard way.
Maybe.
asyncore.py uses the following code:

class dispatcher:
# ...
def __getattr__(sel f, attr):
return getattr(self.so cket, attr)

Now suppose that I'm asking for some attribute not provided by
dispatcher: The lookup mechanism will apparently try to find it
directly and fail, generating an AttributeError; next it will call
__getattr__ to find the attribute. So far, no problems.

But I used a property much like this:
import asyncore
class Peer(asyncore.d ispatcher):

... def _get_foo(self):
... # caused by a bug, several stack levels deeper
... raise AttributeError( 'hidden!')
... foo = property(_get_f oo)
...


You're not supposed to use properties with classic classes.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing." --Alan Perlis
Jul 18 '05 #2
aa**@pythoncraf t.com (Aahz) writes:
In article <87************ @thomas.local>,
Thomas Rast <fo*****@freesu rf.ch.invalid> wrote:

class dispatcher:
# ...
def __getattr__(sel f, attr):
return getattr(self.so cket, attr)
> import asyncore
> class Peer(asyncore.d ispatcher):

... def _get_foo(self):
... # caused by a bug, several stack levels deeper
... raise AttributeError( 'hidden!')
... foo = property(_get_f oo)
...


You're not supposed to use properties with classic classes.


Even if dispatcher was a new-style class, you still get the same
behaviour (or misbehaviour) -- Peer().foo still raises AttributeError
with the wrong message.

A simple workaround is to put a try ... except AttributeError block in
his _get_foo(), which would re-raise with a different error that
wouldn't be caught by getattr. You could even write a property
replacement for that:
class HiddenAttribute Error(Exception ): .... pass def robustprop(fget ):

.... def wrapped_fget(se lf):
.... try:
.... return fget(self)
.... except AttributeError, e:
.... raise HiddenAttribute Error(*e.args)
.... return property(fget=w rapped_fget)

Ideally, I think the better way is if getattr, when raising
AttributeError, somehow reused the old traceback (which would point
out the original problem). I don't know how to do that, though.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)phy sics(dot)mcmast er(dot)ca
Jul 18 '05 #3
David M. Cooke wrote:
Ideally, I think the better way is if getattr, when raising
AttributeError, somehow reused the old traceback (which would point
out the original problem). I don't know how to do that, though.


Maybe a solution could be to put the attribute name in the
AttributeError exception object, and use it in getattr; if the name
doesn't match, the exception is re-raised. It's still not flawless, but
would reduce risk of errors.

Nicolas
Jul 18 '05 #4
Thomas Rast wrote:
I've found out about a fundamental problem of attribute lookup, the
hard way... Is there anything that can be done about this?


It seems to me that the main problem is you're raising an AttributeError
when an attribute is private. AttributeError is only raised when an
attribute is not found. If you found it, but it's private, that's a
different problem. Try raising a custom exception instead of an
AttributeError, if you can.

Jul 18 '05 #5

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

Similar topics

3
2074
by: Johnny | last post by:
Hi, I wonder what is the difference between the built-in function getattr() and the normal call of a function of a class. Here is the details: getattr( object, name) Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object's attributes,
8
1903
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
13
4184
by: Pierre | last post by:
Hi, Sorry in advance, english is not my main language :/ I'd like to customize the result obtained by getattr on an object : if the object has the requested property then return it BUT if the object doesn't has actually this property return something else. In my case, I can't use getattr(object, property, default_value).
4
2427
by: Hole | last post by:
Hi There! I'm trying to use Zope and the product OpenFlow. I got the following error while I was using the built-in function getattr() to retrieve an OpenFlow object: attribute name must be string
4
3686
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin
3
1559
by: Jm lists | last post by:
Hello, Since I can write the statement like: Test whether a path is a directory Why do I still need the getattr() func as below? Test whether a path is a directory
1
20419
by: Sergio Correia | last post by:
This works: # Module spam.py import eggs print getattr(eggs, 'omelet')(100) That is, I just call the function omelet inside the module eggs and evaulate it with the argument 100.
3
3076
numberwhun
by: numberwhun | last post by:
Hello everyone! I am presently going through the "Dive Into Python" tutorial which I obtained from their website. No, this is not for any class, I am self-learning the Python language. I am in Chapter 4 and reading about "Getting Object References with getattr". First, it say in there that, "you can get a reference to a function without knowing its name until run−time, by using the getattr function". That is the first thing that is a...
8
7989
by: Gregor Horvath | last post by:
Hi, class A(object): test = "test" class B(object): a = A() In : B.a.test
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10155
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.