What is a Python code object?

前端 未结 3 1577
花落未央
花落未央 2021-02-01 03:40

While trying to use Python\'s \"exec\" statement, I got the following error:

TypeError: exec: arg 1 must be a string, file, or code object

I do

相关标签:
3条回答
  • 2021-02-01 03:57

    Code objects are described here:

    Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.

    0 讨论(0)
  • 2021-02-01 04:07

    One way to create a code object is to use compile built-in function:

    >>> compile('sum([1, 2, 3])', '', 'single')
    <code object <module> at 0x19ad730, file "", line 1>
    >>> exec compile('sum([1, 2, 3])', '', 'single')
    6
    >>> compile('print "Hello world"', '', 'exec')
    <code object <module> at 0x19add30, file "", line 1>
    >>> exec compile('print "Hello world"', '', 'exec')
    Hello world
    

    also, functions have the function attribute __code__ (also known as func_code in older versions) from which you can obtain the function's code object:

    >>> def f(s): print s
    ... 
    >>> f.__code__
    <code object f at 0x19aa1b0, file "<stdin>", line 1>
    
    0 讨论(0)
  • 2021-02-01 04:13

    There is an excellent blog post by Dan Crosta explaining this topic, including how to create code objects manually, and how to disassemble them again:

    Exploring Python Code Objects

    0 讨论(0)
提交回复
热议问题