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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Jul 28 01:55:33 CEST 2005


On Wed, 27 Jul 2005 14:18:25 -0400, Bill Mill wrote:

> On 7/27/05, Tito <titogarcia_borra_esto at gmail.com> wrote:
>> Hi all:
>> 
>> Is there a metalanguage capability in Python (I know there are many) to
>> call a function having its name in a string?
>> 
>> Something like:
>> __call__("foo")
>> 
>> instead of:
>> foo()
>> 
> 
>>>> def foo(): print "foobarred"
> ...
>>>> foo()
> foobarred
>>>> eval("foo()")
> foobarred

Which is dangerous beyond belief if you are getting your string "foo()"
from a user, and if you aren't, you almost certainly can refactor your
code so you don't need eval.

You know, I really am getting sick of (1) people who ask how to shoot
themselves in the foot and (2) people who cheerfully load the gun and hand
it to them without a word of warning about the consequences. And then
we all act surprised when we learn about the latest virus or security hole
that allows a hostile user to use a music player or paint program to take
over the entire operating system. Or whatever.

"We're all adults here" only works for people who ARE adults. If you have
to ask about eval, you can't be trusted with it without at least a warning.


-- 
Steven.




More information about the Python-list mailing list