Method by name lookup

Will Hartung will.hartung at havasint.com
Fri Nov 3 19:09:20 EST 2000


Alex Martelli wrote in message <8tsu1v015s at news2.newsguy.com>...
>"Will Hartung" <will.hartung at havasint.com> wrote in message
>news:8tsboe0rcs at news1.newsguy.com...
>    [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!

Regards,

Will Hartung
(will.hartung at havasint.com)






More information about the Python-list mailing list