This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: pickle doesn't work in compile/exec
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.5
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Jeff Zhang, brett.cannon
Priority: normal Keywords:

Created on 2017-05-05 00:20 by Jeff Zhang, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg293032 - (view) Author: Jeff Zhang (Jeff Zhang) Date: 2017-05-05 00:20
I want to use pickle in compile/exec, but it doesn't work for me. It only works when I use the global namespace. But I don't want to use global namespace, is there any way for that ? Thanks

>>> a = compile("def f():\n\t'hello'\nimport pickle\npickle.dumps(f)", "<stdin>", "exec")
>>> exec(a)            # works
>>> exec(a, {})        # fails  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in <module>
_pickle.PicklingError: Can't pickle <function f at 0x1050881e0>: it's not the same object as __main__.f
>>> exec(a, {'__name__': '__main__'})   # fails too
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in <module>
_pickle.PicklingError: Can't pickle <function f at 0x1050882f0>: it's not the same object as __main__.f
msg293139 - (view) Author: Brett Cannon (brett.cannon) * (Python committer) Date: 2017-05-05 21:20
It won't work without the global namespace as pickle needs to be able to figure out where the function lives (the function itself doesn't get pickled, just the name of the function).
Date User Action Args
2022-04-11 14:58:46adminsetgithub: 74461
2017-05-05 21:20:27brett.cannonsetstatus: open -> closed

nosy: + brett.cannon
messages: + msg293139

resolution: not a bug
stage: resolved
2017-05-05 00:20:05Jeff Zhangcreate