Python code objects - what are they used for?

What are the options for using Python code objects ? Besides the fact that the interpreter or debugger is used by other useful uses?

Have you interacted directly with code objects? If so, in what situation?

+4
source share
3 answers

The main use of code objects is to separate the static parts of functions (code) from dynamic parts (functions). Code objects are things that are hidden in .pyc files and are created when the code is compiled; functional objects are created from them at runtime when functions are declared. They are displayed to reflect the debugger and often do not require direct use.

All languages ​​that support closure have something similar to them; they simply are not always exposed to the language, as they are in Python, which is more fully reflected than most languages.

You can use code objects to create function objects via types.FunctionType , but this very rarely has 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 
+8
source

When you use the built-in compilation function, it will return a code object, for example:

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

Personally, I used this in applications that support scripts in different plugins: I would just read the plugin from a file, pass it to the compilation function, and then use exec to run when it was needed, which gives you the advantage of speed acceleration, since you only need one compile it into byte code once.

+1
source

Source: https://habr.com/ru/post/1340685/


All Articles