Method by name lookup

Helen Dawson helend at accessone.com
Sun Nov 5 02:44:03 EST 2000


For what it's worth, this is the code used in cmd.py,
which is used by pdb.py, to allow new commands to
be added just by creating functions that start with
do_. It uses the try/except method.

This is from onecmd() in cmd.py:

   try:
    func = getattr(self, 'do_' + cmd)
   except AttributeError:
    return self.default(line)
   return func(arg)


Will Hartung wrote:

> 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