calling python functions using variables

Grant Edwards grante at visi.com
Fri May 19 10:02:04 EDT 2006


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.

-- 
Grant Edwards                   grante             Yow!  This PIZZA symbolizes
                                  at               my COMPLETE EMOTIONAL
                               visi.com            RECOVERY!!



More information about the Python-list mailing list