Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code objects - what are they used for?

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?

like image 495
ElenaT Avatar asked Dec 16 '22 17:12

ElenaT


2 Answers

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
like image 91
Glenn Maynard Avatar answered Dec 30 '22 06:12

Glenn Maynard


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

like image 22
jcubic Avatar answered Dec 30 '22 05:12

jcubic