How to `eval` code with `def`?

Steve D'Aprano steve+python at pearwood.info
Sun May 28 22:39:24 EDT 2017


On Mon, 29 May 2017 11:03 am, 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:

The file encoding cookie must be in the first or second line for Python to
recognise it. Try swapping the encoding cookie and the vim line:

#!/usr/bin/env python
# fileencoding=utf-8:
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1

should work, although I prefer:

# -*- coding: utf-8 -*-


> import dis
> s = """
> def f(x):
>     return x is not None
> """
> print(s)
> eval(s)

If your intention is to call dis on the function, you don't need eval or exec.
Try this instead:

import dis
def f(x):
    return x is not None

dis.dis(f)



If you want the source code too, you can try this:

import inspect
import dis
def f(x):
    return x is not None

dis.dis(f)
print inspect.getsource(f)


but getsource() only works when the function is defined in a .py file, it
doesn't work in the interactive interpreter.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list