Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "code object" mentioned in this TypeError message?

Tags:

python

cpython

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?

like image 274
oneself Avatar asked Apr 24 '11 04:04

oneself


People also ask

What is a code object Python?

Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn't yet been bound into a function. type PyCodeObject. The C structure of the objects used to describe code objects. The fields of this type are subject to change at any time.


1 Answers

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> 
like image 107
Lie Ryan Avatar answered Oct 19 '22 18:10

Lie Ryan