Getting a function name from string

Mike Meyer mwm at mired.org
Thu Nov 3 01:01:46 CET 2005


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> writes:
> "David Rasmussen" <david.rasmussen at gmx.net> wrote in message
> news:436943e0$0$2083$edfadb0f at dtext02.news.tele.dk...
>> If I have a string that contains the name of a function, can I call it?
>> As in:
>>
>> def someFunction():
>> print "Hello"
>>
>> s = "someFunction"
>> s() # I know this is wrong, but you get the idea...
>>
>> /David
>
> Lookup the function in the vars() dictionary.
>
>>>> def fn(x):
> ...   return x*x
> ...
>>>> vars()['fn']
> <function fn at 0x009D67B0>
>>>> vars()['fn'](100)
> 10000

vars() sans arguments is just locals, meaning it won't find functions
in the global name space if you use it inside a function:

>>> def fn(x):
...  print x
... 
>>> def fn2():
...  vars()['fn']('Hello')
... 
>>> fn2()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in fn2
KeyError: 'fn'
>>> 

Using globals() in this case will work, but then won't find functions
defined in the local name space.

For a lot of uses, it'd be better to build the dictionary by hand
rather than relying on one of the tools that turns a namespace into a
dictionary.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list