Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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() function.
Code objects are created using the compile() function and contain various attributes that provide information about the compiled code, such as bytecode, variable names, and filename.
Creating a Code Object
Use the compile() function to create a code object from a string of Python code ?
code_str = """
print("Hello Code Objects")
"""
# Create the code object
code_obj = compile(code_str, '<string>', 'exec')
# Display the code object
print(code_obj)
print(type(code_obj))
<code object <module> at 0x000001D80557EF50, file "<string>", line 2> <class 'code'>
Code Object Attributes
Code objects have numerous attributes that provide metadata about the compiled code ?
code_str = """
def greet(name):
message = f"Hello, {name}!"
return message
"""
code_obj = compile(code_str, '<string>', 'exec')
# Key attributes
print("Filename:", code_obj.co_filename)
print("First line number:", code_obj.co_firstlineno)
print("Variable names:", code_obj.co_varnames)
print("Constants:", code_obj.co_consts)
print("Names used:", code_obj.co_names)
Filename: <string>
First line number: 2
Variable names: ()
Constants: (<code object greet at 0x000001D80557F1A0, file "<string>", line 2>, 'greet')
Names used: ('greet',)
Executing Code Objects
Use exec() to execute a code object ?
code_str = """
x = 10
y = 20
result = x + y
print(f"Result: {result}")
"""
code_obj = compile(code_str, '<string>', 'exec')
# Execute the code object
exec(code_obj)
Result: 30
Common Code Object Attributes
| Attribute | Description |
|---|---|
co_filename |
Source filename |
co_code |
Raw bytecode |
co_varnames |
Local variable names |
co_consts |
Constants used in code |
co_names |
Global names referenced |
Conclusion
Code objects are Python's internal representation of compiled code. Use compile() to create them and exec() to execute them. They're mainly useful for advanced metaprogramming and understanding Python's internals.
