Exception style (was: calling python functions using variables)

Richie Hindle richie at entrian.com
Fri May 19 17:46:58 CEST 2006


[Cameron]
> try:
>     getattr(commands, VARIABLE)()
> except NameError:
>     print >> sys.stderr, "Unknown command", VARIABLE
> 
> 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.

The 'try' block should only include the code that you expect to fail with
the given exception.  Try this instead:

>>> try:
>>>     command = getattr(commands, VARIABLE)
>>> except AttributeError:
>>>     print >> sys.stderr, "Unknown command", VARIABLE
>>> else:
>>>     command()

(Aside: I think AttributeError is correct here, not NameError.)

-- 
Richie Hindle
richie at entrian.com



More information about the Python-list mailing list