Exception style
Ben Finney
bignose+hates-spam at benfinney.id.au
Fri May 19 20:33:17 EDT 2006
"Fredrik Lundh" <fredrik at pythonware.com> writes:
> Cameron Laird wrote:
> > 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()
Gah. As is often the case, Frederick has avoided my mistakes and said
what I wanted to say, better.
--
\ "There are only two ways to live your life. One is as though |
`\ nothing is a miracle. The other is as if everything is." -- |
_o__) Albert Einstein |
Ben Finney
More information about the Python-list
mailing list