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!

0

1 Answer 1

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})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.