On 2020-04-17 2:22 p.m., Adam Preble wrote:
Given this in Python 3.6.8:
from dis import dis
def import_from_test():
from sys import path
dis(import_from_test)
2 0 LOAD_CONST 1 (0)
2 LOAD_CONST 2 (('path',))
4 IMPORT_NAME 0 (sys)
6 IMPORT_FROM 1 (path)
8 STORE_FAST 0 (path)
10 POP_TOP
12 LOAD_CONST 0 (None)
14 RETURN_VALUE
I don't understand why there's a POP_TOP there that I don't get for an
import_name grammatical statement.
IMPORT_NAME needs to eat the top two entries of the stack for level and the
from-list. BTW I don't know what level is for either since my science projects
have always had it be zero, but that's another question.
IMPORT_NAME will the push the module on to the stack.
IMPORT_FROM will import path from the module on the stack, and push that result
on the stack.
STORE_FAST will store path for use, finally "modifying the namespace."
At this point, my conceptual stack is empty. If I POP_TOP then I have nothing
to pop and the world would end. Yet, it doesn't. What am I missing?
You can get an idea of what you're missing if you import multiple names
from a module at once:
>>> def f():
... from sys import path, argv
...
>>> dis.dis(f)
2 0 LOAD_CONST 1 (0)
2 LOAD_CONST 2 (('path', 'argv'))
4 IMPORT_NAME 0 (sys)
6 IMPORT_FROM 1 (path)
8 STORE_FAST 0 (path)
10 IMPORT_FROM 2 (argv)
12 STORE_FAST 1 (argv)
14 POP_TOP
16 LOAD_CONST 0 (None)
18 RETURN_VALUE
As shown here (and confirmed by the doc of the IMPORT_FROM opcode),
IMPORT_FROM loads an attribute from the module on top of the stack, but
doesn't pop the module. The POP_TOP instruction is what does.
--
https://mail.python.org/mailman/listinfo/python-list