Python 是否指的是我的 'from Bla import bla' 语句中的同一个实例?

Does Python refer to the same instance in my 'from Bla import bla' statement?

假设我有以下伪代码。在两个文件中导入 bla 是指 Bla 的 2 个实例还是指同一个实例?换句话说,我可以在 Python 中连接和断开不同文件中的单个连接吗?

bla.py

import socket
class Bla:
  connect(self):
    self.connection = socket.socket(...)
  disconnect(self):
    self.connection.close()
bla = Bla()

hello.py

from bla import bla
bla.connect()

world.py

from bla import bla
bla.disconnect()

是的,在 helloworld 中,bla 都引用相同的实例。

模块是单例,它们的命名空间只有一个副本。第一次导入模块时,顶级语句(函数和生成器之外的所有内容)只执行一次。

模块在 sys.modules mapping 中管理。导入首先确保模块被加载并出现在 sys.modules 中,之后名称被绑定到导入命名空间中。本质上,from bla import blabla = sys.modules['bla'].bla 赋值语句做同样的事情。所以 加载 你的模块到内存只发生一次,你的 bla = Bla() 只执行一次,所有进一步的导入将访问对实例的引用。

来自import statement documentation:

The basic import statement (no from clause) is executed in two steps:

  1. find a module, loading and initializing it if necessary
  2. define a name or names in the local namespace for the scope where the import statement occurs.

[...]

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;
  2. for each of the identifiers specified in the import clauses:
    1. check if the imported module has an attribute by that name
    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    3. if the attribute is not found, ImportError is raised.
    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

(大胆强调我的)。