Re: [Beginner] Calling a function by its name in a string
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: [Beginner] Calling a function by its name in a string

From: Grant Edwards <grante@visi.com>
Date: Wed Jul 27 2005 - 20:38:35 CEST

On 2005-07-27, Paolino <paolo.veronelli@gmail.com> wrote:

>> Is there a metalanguage capability in Python (I know there are many) to
>> call a function having its name in a string?

> eval('foo()') should do, but it's said a bad practice ;)

An alternative to eval() is:

>>> def foo():
... print "foo was called"
...
>>> s = "foo"
>>> globals()[s]()
foo was called
>>>

-- 
Grant Edwards                   grante             Yow!  I'm meditating on
                                  at               the FORMALDEHYDE and the
                               visi.com            ASBESTOS leaking into my
                                                   PERSONAL SPACE!!
Received on Thu Sep 29 17:11:48 2005