SomeClassInstance.[attributename]

Alex Martelli aleaxit at yahoo.com
Mon Nov 6 10:00:28 EST 2000


<tattoom at my-deja.com> wrote in message news:8u6dq7$73l$1 at nnrp1.deja.com...

A bit hard to read, but, I'll try to reformat it...:

"""
Python does provide a built-in function to check for the existence of an
object's attribute:
    hasattr(object, name)
What puzzles me to no end, is the fact one straight (IMHO) corollary to
the above functionality doesn't seem to exist (at least I can't find
it :-). Namely, the possibility to access an instance's attribute in a
'parameterized' (is that a correct word?) way.

Assume that Foo is an instance of some class:

    theAttribute = 'fubar'
    if hasattr(Foo, theAttribute):
        fubar = Foo.[theAttribute]

Where Foo.[theAttribute] would yield Foo.fubar
You get my point. Is there a way in Python (as elegant and straightforward
as this one) to achieve the above?If not, I'd be interested in seeing
suggestions on how to implement it.
"""


I think the built-in getattr function is what you want:

    if hasattr(Foo, theAttribute):
        fubar = getattr(Foo, theAttribute)

Most often, you don't need to 'protect' the getattr call
with an hasattr test, since getattr can take a third
argument, the 'default value' to return if the object
does NOT have the attribute.

For example, the code:

    if hasattr(Foo, theAttribute):
        fubar = getattr(Foo, theAttribute)
    else:
        fubar = 23

can be more concisely, clearly, & speedily expressed as just:

    fubar = getattr(Foo, theAttribute, 23)


Alex






More information about the Python-list mailing list