doUWannaBuildASnowMan
doUWannaBuildASnowMan

Reputation: 461

does the module have got code object attribute?

according to explore to the code object

function has code object attribute for the code inside of it, and the code object has bytecode attribute. By executing the bytecode, python execute the function code.

  1. does module object also have got code object attribute for all the code inside?
  2. whether python execute the code inside the module by executing the bytecode attribute of code object of the module.
  3. If not, what is the operation done by python when instantiating the module object when we import the module

Upvotes: 0

Views: 71

Answers (1)

BlackJack
BlackJack

Reputation: 4689

In CPython modules don't have a code object attached at runtime. *.pyc files contain the bytecode for the module, but it is discarded after executing it at import, because after importing it is not needed any more.

Given it is the first import of a module, the runtime checks if there is an up to date cached bytecode file. If there is, it is loaded and the code object is executed in the context of a new module object. If there isn't, the source is compiled to bytecode, possibly written to a file, and executed in the context of a new module object.

So how to get at the bytecode of a module then? If you have a bytecode file, you can unmarshal the bytecode from it. Assuming we have a module which just contains print('Hello, World!'):

>>> data = open('__pycache__/test.cpython-35.pyc', 'rb').read()
>>> import imp
>>> data.startswith(imp.get_magic())
True
>>> import marshal
>>> marshal.loads(data[len(imp.get_magic())+8:])
<code object <module> at 0x7f47b4fb5b70, file "/home/bj/test.py", line 4>
>>> import dis
>>> dis.dis(marshal.loads(data[len(imp.get_magic())+8:]))
  4           0 LOAD_NAME                0 (print)
              3 LOAD_CONST               0 ('Hello, World!')
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

If you just have the source code: compile() it:

>>> compile("print('Hello, World!')", '<input>', 'exec')
<code object <module> at 0x7f47b4fc0f60, file "<input>", line 1>
>>> dis.dis(compile("print('Hello, World!')", '<input>', 'exec'))
  1           0 LOAD_NAME                0 (print)
              3 LOAD_CONST               0 ('Hello, World!')
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE       13 RETURN_VALUE

Upvotes: 1

Related Questions