【问题标题】:Surprisingly smart python import behaviour : what's happening under the hood?令人惊讶的智能 python 导入行为:幕后发生了什么?
【发布时间】:2021-05-17 10:25:43
【问题描述】:

Python 导入是 confusing,但我以为我终于理解了它们,直到我偶然发现了这种行为(在 3.9.1 中)。这里发生了什么?

采用这个包结构:

countries/
├── __init__.py  # from . import greece
├── greece.py
└── spain.py

如果我做import countries,命名空间dir(countries) 只包含greece,正如预期的那样。

但如果我开始我的会话:

from countries import spain
import countries

命名空间dir(countries) 包含greecespain

我知道在我第一次导入时__init__.py 在后台运行。我不明白的是python如何记住在countries命名空间中同时包含greecespain。是否在运行from countries import spain 之后将countries 命名空间保存在某个地方,然后运行import countries 只是将其添加到本地命名空间?

【问题讨论】:

  • 您可以随时打印sys.path 来查看导入情况
  • 如果你有一些时间可以燃烧,David Beazley 的这个演讲是我最喜欢的 Python 包之一。 dabeaz.com/modulepackage
  • 真的很有趣,谢谢!

标签: python python-3.x import python-import


【解决方案1】:

你是对的。导入模块时,python 将其保存在导入模块列表中。当你 from countries import spain 然后导入根时,python 知道 spain 是父 countries 的子模块。所以当你import countries 它只是将你不需要的子模块添加到父模块。

查看实际逻辑:https://github.com/python/cpython/blob/f32c7950e0077b6d9a8e217c2796fc582f18ca08/Lib/importlib/_bootstrap.py#L1007

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2021-08-20
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多