36

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 don't want to pass in a string or a file, but what is a code object, and how do I create one?

2

4 Answers 4

37

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>
3
  • 10
    The bit that puzzles me about the OP's question (and acceptance of this answer) is that if they're going to pass a string to compile, most of the time they may as well pass it directly to exec and let exec compile it to a code object behind the scenes. The only reason to call compile directly is if the application has a specific need to separate the compilation and execution steps (e.g. the same code object may be invoked more than once, or the syntax check is desired when the code is entered, even if it won't be run until later).
    – ncoghlan
    Commented Apr 24, 2011 at 16:53
  • What does the line number indicate in the output of compile command?
    – YatShan
    Commented Dec 17, 2019 at 7:47
  • @YatShan: It's not the output of the compile command. It's the string return from the automatic call to repr(f.__code__) the Python interactive shell made to so the value of the last expression typed-in (i.e. f.__code__). It says "line 1" because that's the line number of the function def.
    – martineau
    Commented Sep 12, 2021 at 12:52
30

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

1
  • 3
    Good link. For posterity, if the link becomes dead: the page discusses creating code objects via compile, understanding the object's internals, and looks at the underlying byte code a bit. Commented Apr 6, 2019 at 16:40
18

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

Disassemble code with dis.dis to see what it contains

A pretty fundamental thing you can do to inspect a code object is to disassemble it as mentioned on the link from Daniel's answer:

import ast
import dis

myast = ast.parse('''def inc(i):
    return i + 1

print(inc(2))
''')
# print(ast.dump(myast, indent=2))
print(ast.unparse(myast))
code = compile(myast, 'mymodule', 'exec')
exec(code)
dis.dis(code)

Output:

def inc(i):
    return i + 1
print(inc(2))
3
  0           0 RESUME                   0

  1           2 LOAD_CONST               0 (<code object inc at 0x7f85fbfae800, file "mymodule", line 1>)
              4 MAKE_FUNCTION            0
              6 STORE_NAME               0 (inc)

  4           8 PUSH_NULL
             10 LOAD_NAME                1 (print)
             12 PUSH_NULL
             14 LOAD_NAME                0 (inc)
             16 LOAD_CONST               1 (2)
             18 PRECALL                  1
             22 CALL                     1
             32 PRECALL                  1
             36 CALL                     1
             46 POP_TOP
             48 LOAD_CONST               2 (None)
             50 RETURN_VALUE

Disassembly of <code object inc at 0x7f85fbfae800, file "mymodule", line 1>:
  1           0 RESUME                   0

  2           2 LOAD_FAST                0 (i)
              4 LOAD_CONST               1 (1)
              6 BINARY_OP                0 (+)
             10 RETURN_VALUE

So we can see that this actually explains what code actually contains, which is Python bytecode, and which is documented on the dis module itself: https://docs.python.org/3.11/library/dis.html

Tested on Python 3.11.4, Ubuntu 23.04.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.