"Paul McGuire" <[EMAIL PROTECTED]> writes:
> "David Rasmussen" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> 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 <[EMAIL PROTECTED]>                  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to