calling a function indirectly

Andrae Muys amuys at shortech.com.au
Fri Feb 22 01:55:59 CET 2002


Michal Wallace <sabren at manifestation.com> wrote in message news:<mailman.1014185673.27565.python-list at python.org>...
> On Tue, 19 Feb 2002, Rajarshi Guha wrote:
> 
> > Hi,
> >   is it possible to have a variable contain a function name, and use the 
> > variable to call the function? 
> > An example:
> > 
> > def func:
> >    some code
> > 
> > funcvar = 'func'
> > 
> > Now use funcvar (somehow!) to call func
> 
> 
> I also think the easiest thing to use is funcvar = func,
> but if for some reason it has to be a string, you can
> use exec, or:
> 
> locals()[funcvar]("whatever")
> 

Note that this only works if func is in the local scope, however if it
is in an enclosing scope there is no analogous function to use in
place of locals().

Quoting from PEP227 (Statically Nested Scopes)

locals() / vars()
    These functions return a dictionary containing the current scope's
    local variables.  Modifications to the dictionary do not affect
    the values of variables.  Under the current rules, the use of
    locals() and globals() allows the program to gain access to all
    the namespaces in which names are resolved.

    An analogous function will not be provided for nested scopes.
    Under this proposal, it will not be possible to gain
    dictionary-style access to all visible scopes.

== end quote ==

So you will need to revert to the eval() hack :(.

I am curious to know why an analogous function wasn't provided?  Or
more presisely why the rationale behind the current behaviour wasn't
captured in the PEP?

OTOH, you are almost certainly better off using the function directly,
if necessary creating your own dictionary to store them ie...

func = func1
func()

or

ops = { 'func1':func1, 'func2':func2, 'func3':func3 }
func = 'func1'
ops[func]()

etc.

Andrae Muys



More information about the Python-list mailing list