How to `eval` code with `def`?

MRAB python at mrabarnett.plus.com
Sun May 28 21:19:00 EDT 2017


On 2017-05-29 02:03, Peng Yu wrote:
> Hi,
> 
> I got the following error when I try to eval the following code with
> def. Does anybody know what is the correct way to evaluation python
> code that contains `def`? Thanks.
> 
> $ cat ./main.py
> #!/usr/bin/env python
> # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
> 
> import dis
> s = """
> def f(x):
>      return x is not None
> """
> print(s)
> eval(s)
> $ ./main.py
> 
> def f(x):
>      return x is not None
> 
> Traceback (most recent call last):
>    File "./main.py", line 10, in <module>
>      eval(s)
>    File "<string>", line 2
>      def f(x):
>        ^
> SyntaxError: invalid syntax
> 
'eval' expects an expression, e.g. "1 + 2", not statements.

What you should be using instead is 'exec'.



More information about the Python-list mailing list