2

I have a problem with code snippet founded on https://stackoverflow.com/a/10303539/4113228

When I try to compile:

import types
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {})
dynf()

in file test.py using python2.7, everything working fine, but when I try with python3.5 I get:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dynf()
  File "dyn.py", line 1, in <module>
NameError: name 'print' is not defined

I'm new in python coding and I completly get stuck at this.. Many thanks for any help!

kamilw7
  • 33
  • 3

1 Answers1

3

The problem is that you're passing an empty dict as globals - because of this, the compiled code can't access global variables or builtins.

To allow access to builtin functions, use

import builtins
dynf = types.FunctionType(compile('print("wow")', 'dyn.py', 'exec'), {'__builtins__':builtins})
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149