I am trying to dump a compiled piece of compiled Python code using either marshal
or dill
.
The source is compiled with compiled(src, "<source>", "exec", optimize=2)
, the compiled code does run well.
However, when the compiled code is dumped with either dill
or marshal
, and loaded again,
the code raises NameError
as in the example below.
Code example:
- File
source.py
import sympy pp = sympy.pprint x = sympy.Symbol("x") def p(*args): try: pp(*args) except TypeError: print(*args) p(5*x+1)
- File
compiler.py
import dill #import marshal with open("source.py") as fp: src = fp.read() compiled = compile(src, "<source>", "exec", optimize=2) exec(compiled) # ok obj = dill.dumps(compiled) loaded = dill.loads(obj) exec(loaded) # NameError: name "pp" is not defined
How can I fix this? And if it is intended behaviour, is there any alternatives to serialise/deserialise the compiled code? (I am not concerned about security yet.)