开发者

Python code objects - what are they used for?

What are the uses of Python code obje开发者_如何学编程cts? 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


When you use the built-in compile function it will return a code object, like this:

>>> c = compile("print 'Hello world'", "string", "exec")
<code object <module> at 0xb732a4e8, file "string", line 1>
>>> exec(c)
Hello world
>>> 

Personally, I've used this in applications that supports scripting in different plug-ins: I would just read the plug-in from a file, pass it to the compile function and then use exec to run it whenever it was needed, which gives the advantage of a speed boost as you only have to compile it once to byte code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜