Method by name lookup

Will Hartung will.hartung at
Sat Nov 4 01:09:20 CET 2000

Alex Martelli wrote in message <8tsu1v015s at>...
>"Will Hartung" <will.hartung at> wrote in message
>news:8tsboe0rcs at
>    [snip]
>> I can't use something like:
>> funcitem = instance.funcname
>> because funcname may not exist in the object.
>While the already-suggested getattr is surely best in this
>case, I just wanted to point out that just because something
>might fail doesn't mean you can attempt it anyway -- often,
>the 'try, but catch a possible exception' attempt comes in
>very useful.  So, as a general approach, though certainly
>not optimal here, do remember that, e.g.,...:
>    try: funcitem = instance.funcname
>    except AttributeError: funcitem = None
>is roughly equivalent to the more concise & specific:
>    funcitem = getattr(instance, 'funcname', None)

Yes, of course. But for my case, it's a completely dynamic lookup. I'm
constructing method names based on properties, so, I can't do "funcitem =
instance.funcname" anyway.

But thanx for the tips!


Will Hartung
(will.hartung at

More information about the Python-list mailing list