What are the uses of Python code objects? Besides being used by the interpreter or debugger what other useful usages do they have?
Have you interacted directly with code objects? If yes, in what situation?
The primary use of code objects is to separate the static parts of functions (code) from the dynamic parts (functions). Code objects are the things that are stashed in .pyc files, and are created when code is compiled; function objects are created from them at runtime when functions are declared. They're exposed for debugger reflection and don't often need to be used directly.
All languages that support closures have something like them; they're just not always exposed to the language as they are in Python, which has more comprehensive reflection than most languages.
You can use code objects to instantiate function objects via types.FunctionType
, but that very rarely has any practical use--in other words, don't do this:
def func(a=1):
print a
func2 = types.FunctionType(func.func_code, globals(), 'func2', (2,))
func2()
# 2
You can use them if you want to pickle functions.
two recipes:
http://code.activestate.com/recipes/572213-pickle-the-interactive-interpreter-state/
http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-7-sect-6.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With