Exception style (was: calling python functions using variables)

Carl Banks invalidemail at aerojockey.com
Sat May 20 04:48:24 EDT 2006


Fredrik Lundh wrote:
> Cameron Laird wrote:
>
> > Guys, I try--I try *hard*--to accept the BetterToAskForgiveness
> > gospel, but this situation illustrates the discomfort I consistently
> > feel:  how do I know that the NameError means VARIABLE didn't resolve,
> > rather than that it did, but that evaluation of commands.VARIABLE()
> > itself didn't throw a NameError?  My usual answer:  umm, unless I go
> > to efforts to prevent it, I *don't* know that didn't happen.
>
> two notes:
>
> 1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.
>
> 2) as you point out, doing too much inside a single try/except often results in hard-
> to-find errors and confusing error messages.  the try-except-else pattern comes in
> handy in cases like this:
>
>     try:
>         f = getattr(commands, name)
>     except AttributeError:
>         print "command", name, "not known"
>     else:
>         f()

What if commands were an instance of this class:

class CommandClass:
    ....
    def __getattr__(self,attr):
        try:
            return self.dircontenst[attr]
        except KeyError:
            raise AttributeError

The call to getattr manages to raise AttributeError even though the
command is known. Yes, self.dircontents[attr] does exist and is valid
in this example, but it still raises AttributeError because dircontents
is spelled wrong.

I make this silly example to point out that Python's dynamicism is a
possible pitfall with ETAFTP even if you're careful.  It's something
worth keeping in mind.

Another example, much more realistic: GvR says don't use callable(),
just try calling it and catch CallableError (or whatever it is).  Of
course, that error can be raised inside the function; and in this case,
there's no way to isolate only the part you you're checking for an
exception.


Carl Banks




More information about the Python-list mailing list