Exception style (was: calling python functions using variables)

Cameron Laird claird at lairds.us
Fri May 19 16:41:13 CEST 2006


In article <126rjus43k450df at corp.supernews.com>,
Grant Edwards  <grante at visi.com> wrote:
>On 2006-05-19, bruno at modulix <onurb at xiludom.gro> wrote:
>
>>> Either deal with the resulting NameError exception (EAFP[0])
>>
>> try:
>>   getattr(commands, VARIABLE)()
>> except NameError:
>>   print >> sys.stderr, "Unknown command", VARIABLE
>>
>>> or test
>>> first whether the attribute exists (LBYL[1]).
>>
>> command = getattr(commands, VARIABLE, None)
>> if command is None:
>>   print >> sys.stderr, "Unknown command", VARIABLE
>> else:
>>   command()
>>
>> I'd go for the first solution.
>
>Me too.  Assuming the user isn't clueless, the normal case is
>where the command exists.  Write code for the normal case and
>use the exception that occurs for exceptional cases.
			.
			.
			.
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.



More information about the Python-list mailing list