4

How to save the code object (_ _ code _ _) in file?

>>> c
<code object foo at 0x022E7660, file "<console>", line 1>
>>> pickle.dump(c, f)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'code'>: attribute lookup builtins.code failed
>>> f.write(c)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'code' does not support the buffer interface
1
  • 1
    Code objects are inherently platform-dependent, and pickle is a platform-independent format. There is no easy way to represent a code object platform-independently, but usually you don't need to. What are you trying to achieve? Commented Oct 28, 2011 at 11:37

1 Answer 1

10

Not sure what you are trying to do but you can use the marshal module for this:

>>> import marshal
>>> def f():
...    print 'f'
>>> marshal.dump(f.__code__, open('test.dump'))
>>> code = marshal.load(open('test.dump'))
>>> f.__code__ == code
True
>>> import dis
>>> dis.dis(code)
  2           0 LOAD_CONST               1 ('f')
              3 PRINT_ITEM          
              4 PRINT_NEWLINE       
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE  
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.