calling python functions using variables

Ben Finney bignose+hates-spam at benfinney.id.au
Fri May 19 20:31:40 EDT 2006


bruno at modulix <onurb at xiludom.gro> writes:

> Ben Finney wrote:
> > You'll also need to anticipate the situation where the value bound
> > to VARIABLE is not the name of an attribute in 'commands'.
> > 
> > Either deal with the resulting NameError exception (EAFP[0])
> 
> try:
>   getattr(commands, VARIABLE)()
> except NameError:
>   print >> sys.stderr, "Unknown command", VARIABLE

No. As another poster points out, that will mistakenly catch NameError
exceptions raised *inside* the function.

When catching exceptions, be sure that your 'try' block is only doing
the minimum of stuff that you want exceptions from, so you know what
they mean when they occur.

    try:
        this_command = getattr(commands, VARIABLE)
    except NameError:
        print >> sys.stderr, "Unknown command '%s'" % VARIABLE
    this_command()

> > 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.

With the caveats mentioned above, yes, I agree.

-- 
 \         "I was arrested today for scalping low numbers at the deli. |
  `\                  Sold a number 3 for 28 bucks."  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list