Exception style (was: calling python functions using variables)

Fredrik Lundh fredrik at pythonware.com
Fri May 19 11:40:16 EDT 2006


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

</F> 






More information about the Python-list mailing list