Method by name lookup

Alex Martelli aleaxit at yahoo.com
Thu Nov 2 18:36:46 EST 2000


"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)


Alex






More information about the Python-list mailing list