Python 手动加载模块don';我没有所有的属性

Python 手动加载模块don';我没有所有的属性,python,python-3.x,python-module,python-importlib,Python,Python 3.x,Python Module,Python Importlib,我手动加载模块请求。我以同样的方式连续做了两次,一个接一个。该模块已安装并位于默认的站点软件包中。剧本是: specification = importlib.util.spec_from_file_location( name='requests', location='/usr/local/lib/python3.7/site-packages/requests/__init__.py', ) module = importlib.util.module_from_spec(

我手动加载模块
请求
。我以同样的方式连续做了两次,一个接一个。该模块已安装并位于默认的
站点软件包中
。剧本是:

specification = importlib.util.spec_from_file_location(
    name='requests',
    location='/usr/local/lib/python3.7/site-packages/requests/__init__.py',
)
module = importlib.util.module_from_spec(spec=specification)
sys.modules[module.__name__] = module
specification.loader.exec_module(module=module)

requests = module
print(requests)
print(len(dir(requests)))
print(requests.api)

print()
print()

specification = importlib.util.spec_from_file_location(
    name='requests',
    location='/usr/local/lib/python3.7/site-packages/requests/__init__.py',
)
module = importlib.util.module_from_spec(spec=specification)
sys.modules[module.__name__] = module
specification.loader.exec_module(module=module)

requests = module
print(requests)
print(len(dir(requests)))
print(requests.api)
输出如下所示:

module 'requests' from '/usr/local/lib/python3.7/site-packages/requests/__init__.py'>
66
<module 'requests.api' from '/usr/local/lib/python3.7/site-packages/requests/api.py'>


module 'requests' from '/usr/local/lib/python3.7/site-packages/requests/__init__.py'>
53
Traceback (most recent call last):
...
    print(requests.api)
AttributeError: module 'requests' has no attribute 'api'
module'requests'来自'/usr/local/lib/python3.7/site packages/requests/_init__;.py'>
66
模块“请求”来自“/usr/local/lib/python3.7/site packages/requests/\uuuu init\uuuu.py”>
53
回溯(最近一次呼叫最后一次):
...
打印(requests.api)
AttributeError:模块“请求”没有属性“api”
如果我看一下
目录的响应,第一个目录的属性将比第二个目录的属性多得多。例如,
api
属性显示在第一个模块中,但不在第二个模块中

我试过(其中任何一个都不起作用):

  • 每次加载后,
    globals()
  • del sys.modules[模块名称]
    每次加载前后

我错过了什么?提前感谢。

导入请求
导入包
请求
(包括其他模块)。您的
importlib
仅基于文件
requests/\uuuu init\uuuuu.py
创建一个新模块,该文件与包
requests
@chepner不同,但为什么我的第一次导入与我的
导入请求具有相同的属性;打印(len(dir(requests))
如果我使用
importlib
导入它,
请求
包的一些属性直接在
\uuu init\uuuuuuuuuupy
中设置<代码>api
不是其中之一
\uuuu init\uuuuuuuuuuuuuuuuupy
使用.api import*
中的
,从而导入和重新导入在
api.py
中定义的所有名称,但不导出名称
api
本身。您认为手动加载
请求/\uuuuuuuuuuuuuuuuuuuuuuuuupy
有什么好处?(或者您只是在试验
importlib
是如何工作的?)但是为什么结果与上面两个相同的导入结果不同呢。我理解你的回答是对不同问题的回答(导入和导入的不同甜菜是什么)。