这是一个奇怪的问题,我最初的反应是,你可能最好做一些其他事情来完成你想要做的任何事情.但它仍然是一个有趣的问题,所以这是我对它的破解:我使原始代码源成为代码对象的未使用常量.
import types def comp(source, *args, **kwargs): """Compile the source string; takes the same arguments as builtin compile(). Modifies the resulting code object so that the original source can be recovered with decomp().""" c = compile(source, *args, **kwargs) return types.CodeType(c.co_argcount, c.co_nlocals, c.co_stacksize, c.co_flags, c.co_code, c.co_consts + (source,), c.co_names, c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab, c.co_freevars, c.co_cellvars) def decomp(code_object): return code_object.co_consts[-1]
>>> a = comp('2 * (3 + x)', '', 'eval') >>> eval(a, dict(x=3)) 12 >>> decomp(a) '2 * (3 + x)'