为什么这个 "from bar import *" 使用导入模块中未定义的名称污染我的名称空间?

Why does this "from bar import *" pollute my namespace with a name not defined in the imported module?

我以为我明白了what "import *" did and its potential dangers,但显然不是。

我有:

foo.py:

from datetime import datetime
from bar import *
print(datetime.now())

bar.py:

import datetime

运行的结果foo.py异常:

AttributeError: module 'datetime' has no attribute 'now'

datetime 是一个模块,而 datetime.datetime 是一个类型。 from datetime import datetime 使 foo.py 中的 datetime 引用类型,但随后的 from bar import * 以某种方式再次引用模块。

删除 from bar import * 会使异常消失。

但是为什么 from bar import * 会用模块 datetime 污染我的命名空间? datetime 是在 bar 中导入的模块,但未在此处定义。我错过了什么?

bar 模块 确实 定义了名称 datetime。声明

import datetime

bar模块中创建模块级datetime变量,并将该变量绑定到datetime模块。 import * 选择此名称的方式与选择其他名称的方式相同。

import * 不关心对象的创建位置。它并不关心 datetime 模块本身来自其他文件。 datetime 名称存在于 bar 中,因此该名称被导入。