Mô tả
Code object là biểu diễn nội bộ của CPython cho một khối code thực thi (module, function, class body, lambda...). Không gọi trực tiếp được, cần exec() hoặc eval().
Tạo Code Object
code_str = """
print("Hello Code Objects")
"""
# Compile source string thành code object
# mode: 'exec' (statements), 'eval' (expression), 'single' (interactive)
code_obj = compile(code_str, '', 'exec')
print("Code object:", code_obj)
print("Type:", type(code_obj))
Đầu ra
Code object: at 0x..., file "", line 2>
Type:
Thuộc tính quan trọng của Code Object
| Attribute | Mô tả |
|---|---|
co_name | Tên function/module |
co_filename | Tên file nguồn |
co_firstlineno | Số dòng đầu tiên |
co_argcount | Số positional arguments |
co_varnames | Tuple tên biến cục bộ |
co_consts | Tuple các hằng số |
co_code | Bytecode thô (bytes) |
co_flags | Flags (generator, coroutine, etc.) |
Ví dụ khám phá Function Code Object
def greet(name, greeting="Hello"):
message = f"{greeting}, {name}!"
return message
code_obj = greet.__code__
print("Name:", code_obj.co_name)
print("Filename:", code_obj.co_filename)
print("First line:", code_obj.co_firstlineno)
print("Arg count:", code_obj.co_argcount)
print("Var names:", code_obj.co_varnames)
print("Constants:", code_obj.co_consts)
print("Bytecode (hex):", code_obj.co_code.hex())
Đầu ra
Name: greet Filename:First line: 1 Arg count: 2 Var names: ('name', 'greeting', 'message') Constants: (None, 'Hello', ', ', '!') Bytecode (hex): 640000... (mã bytecode)
Thực thi Code Object
code_str = "x = 10\ny = 20\nresult = x + y" code_obj = compile(code_str, '', 'exec') namespace = {} exec(code_obj, namespace) print(namespace['result']) # 30 # Hoặc eval cho expression expr_code = compile("3 + 4", ' ', 'eval') print(eval(expr_code)) # 7
Ứng dụng nâng cao
- Dynamic code generation: Tạo code object runtime.
- Bytecode manipulation: Sửa bytecode (rất nâng cao, dùng
bytecodelib). - Debugging/Profiling: Phân tích code object để hiểu performance.
- Serialization:
marshalmodule để serialize code object.
Lưu ý: Code object là detail của CPython. Các implementation khác (PyPy, Jython) có thể khác. Code production hiếm khi thao tác trực tiếp code object.