What is a Python code object?

前端 未结 3 1607
花落未央
花落未央 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 04:07

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

    >>> compile('sum([1, 2, 3])', '', 'single')
     at 0x19ad730, file "", line 1>
    >>> exec compile('sum([1, 2, 3])', '', 'single')
    6
    >>> compile('print "Hello world"', '', 'exec')
     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__
    ", line 1>
    

提交回复
热议问题