Exception style (was: calling python functions using variables)
fredrik at pythonware.com
Fri May 19 17:40:16 CEST 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.
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:
f = getattr(commands, name)
print "command", name, "not known"
More information about the Python-list