Python Code Objects


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. Though code objects represent some piece of executable code, they are not, by themselves, directly callable. To execute a code object, you must use the exec keyword.

In the below example we see how the code objects are created for a given piece of code and what are the various attributes associated with hat code object.

Example

 Live Demo

code_str = """
print("Hello Code Objects")
"""
# Create the code object
code_obj = compile(code_str, '<string>', 'exec')
# get the code object
print(code_obj)
#Attributes of code object
print(dir(code_obj))
# The filename
print(code_obj.co_filename)
# The first chunk of raw bytecode
print(code_obj.co_code)
#The variable Names
print(code_obj.co_varnames)

Output

Running the above code gives us the following result −

<code object <module> at 0x000001D80557EF50, file "<string>", line 2>
['__class__', '__delattr__', '__dir__', '__doc__', ……., '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', …..,posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
<string>
b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00'
()

Updated on: 25-Jan-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements