calling python functions using variables

Ben Finney bignose+hates-spam at benfinney.id.au
Fri May 19 05:57:15 EDT 2006


Peter Otten <__peter__ at web.de> writes:

> creo wrote:
> > what i want to do is
> > commands.VARIABLE()
> > where VARIABLE holds the name of the function which i want to execute
> > and depends on what the user has typed
> 
> You want
> 
> getattr(commands, VARIABLE)()

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]) or test
first whether the attribute exists (LBYL[1]).

[0] Easier to Ask Forgiveness than Permission
[1] Look Before You Leap

-- 
 \       "Our products just aren't engineered for security."  -- Brian |
  `\             Valentine, senior vice-president of Microsoft Windows |
_o__)                                                      development |
Ben Finney




More information about the Python-list mailing list