Getting a function name from string

Bengt Richter bokr at oz.net
Thu Nov 3 02:22:16 EST 2005


On Wed, 02 Nov 2005 19:01:46 -0500, Mike Meyer <mwm at mired.org> wrote:

>"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.
IMO it would be nice if name lookup were as cleanly
controllable and defined as attribute/method lookup.
Is it a topic for py3k?

Regards,
Bengt Richter



More information about the Python-list mailing list