Do eval() and exec not accept a function definition? (like 'def foo: pass) ?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Jun 24 03:17:40 CEST 2007


On Sat, 23 Jun 2007 19:58:32 +0000, vasudevram wrote:

> 
> Hi group,
> 
> Question: Do eval() and exec not accept a function definition? (like
> 'def foo: pass) ?

eval() is a function, and it only evaluates EXPRESSIONS, not code blocks. 

eval("2+3") # works
eval("x - 4") # works, if x exists
eval("print x") # doesn't work

exec is a statement, and it executes entire code blocks, including
function definitions, but don't use it. Seriously.

ESPECIALLY don't use it if you are exec'ing data collected from untrusted
users, e.g. from a web form.


> I wrote a function to generate other functions using something like
> eval("def foo: ....")
> but it gave a syntax error ("Invalid syntax") with caret pointing to
> the 'd' of the def keyword.

You don't need eval or exec to write a function that generates other
functions. What you need is the factory-function design pattern:


def factory(arg):
    def func(x):
        return x + arg
    return func

And here it is in action:

>>> plus_one = factory(1)
>>> plus_two = factory(2)
>>> plus_one(5)
6
>>> plus_two(5)
7



-- 
Steven.




More information about the Python-list mailing list