import python as mulan_Python子模块:“import as”vs“import”

博客探讨了Python中`import`语句的字节码行为差异,特别是在涉及导入循环时。它通过`dis`模块展示了`import a.b`、`import a.b as c`和`from sys import path`的字节码,解释了为何在导入循环中会出现不同的行为。文章还提到了`sys.path`作为模块名的情况,以及如何影响`LOAD_ATTR`操作码的执行。
摘要由CSDN通过智能技术生成

这在Python Ideas中讨论过,但是import foo.bar as eggs与{}不同。它们生成不一致的字节码。在The root cause is the import cycle. I played around with dis and found the following (I suspect others have already found this but the thread was hard to follow for me initially):>>> dis.dis('import a.b')

1 0 LOAD_CONST 0 (0)

2 LOAD_CONST 1 (None)

4 IMPORT_NAME 0 (a.b)

6 STORE_NAME 1 (a)

8 LOAD_CONST 1 (None)

10 RETURN_VALUE

>>>compared to

^{pr2}$

What this shows is that the implementation of "import a.b" and "import a.b as c" are different. The former calls import('a.b', ...) which returns the module 'a' and stores that in the variable 'a'. In the OP's case, because of the import cycle, while sys.modules['a.b'] exists, module 'a' does not yet have the attribute 'b'. That's the reason that in the latter example, the LOAD_ATTR opcode fails.>>> dis("import sys.path as path")

1 0 LOAD_CONST 0 (0)

3 LOAD_CONST 1 (None)

6 IMPORT_NAME 0 (sys.path)

9 LOAD_ATTR 1 (path)

12 STORE_NAME 1 (path)

15 LOAD_CONST 1 (None)

18 RETURN_VALUEFor "import sys.path as path", the given module name is "sys.path", and the "from list" entry on the stack is None. This fails before it even reaches the LOAD_ATTR line, since "sys.path" isn't an importable module. Changing LOAD_ATTR to IMPORT_FROM would thus have no effect on its behaviour.>>> dis("from sys import path")

1 0 LOAD_CONST 0 (0)

3 LOAD_CONST 1 (('path',))

6 IMPORT_NAME 0 (sys)

9 IMPORT_FROM 1 (path)

12 STORE_NAME 1 (path)

15 POP_TOP

16 LOAD_CONST 2 (None)

19 RETURN_VALUEFor "from sys import path", the given module name is "sys", and the "from list" entry on the stack is a tuple containing the string "path". This works, since "sys" is importable and it has a "path" attribute.

我想你得等3.7版或者换个进口。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值