在python中,如何知道何时导入子模块与主模块是必需的?

在python中,如何知道何时导入子模块与主模块是必需的?,python,import,Python,Import,我有一个关于这个的后续初学者问题: 如何知道子模块的导入何时是显式的?我可以在参数模块中的help()或dir()中找到它吗?如果是,在哪里?简短的回答是您应该能够使用dir(),但不能使用help() 答案很长: 让我们以Python 3.8.5的多处理模块为例(这就是我所拥有的)。我的安装目录结构的一部分是: Python38 Lib multiprocessing dummy __init__.py

我有一个关于这个的后续初学者问题:


如何知道子模块的导入何时是显式的?我可以在参数模块中的help()或dir()中找到它吗?如果是,在哪里?

简短的回答是您应该能够使用
dir()
,但不能使用
help()

答案很长:

让我们以Python 3.8.5的
多处理
模块为例(这就是我所拥有的)。我的安装目录结构的一部分是:

Python38
    Lib
        multiprocessing
            dummy
                __init__.py
                connection.py
            __init__.py
            pool.py
现在,我导入
多处理
模块,并对其执行
dir
,观察到
虚拟
模块均未出现:

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import multiprocessing
>>> dir(multiprocessing)
['Array', 'AuthenticationError', 'Barrier', 'BoundedSemaphore', 'BufferTooShort', 'Condition', 'Event', 'JoinableQueue', 'Lock', 'Manager', 'Pipe', 'Pool', 'Process', 'ProcessError', 'Queue', 'RLock', 'RawArray', 'RawValue', 'SUBDEBUG', 'SUBWARNING', 'Semaphore', 'SimpleQueue', 'TimeoutError', 'Value', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'active_children', 'allow_connection_pickling', 'context', 'cpu_count', 'current_process', 'freeze_support', 'get_all_start_methods', 'get_context', 'get_logger', 'get_start_method', 'log_to_stderr', 'parent_process', 'process', 'reducer', 'reduction', 'set_executable', 'set_forkserver_preload', 'set_start_method', 'sys']
而且,如果我尝试访问这些模块,肯定会出现错误:

>>> multiprocessing.pool
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'multiprocessing' has no attribute 'pool'
>>> multiprocessing.dummy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'multiprocessing' has no attribute 'dummy'
您可以看到包含了
dummy
pool
,但我们知道必须显式导入这些子模块

现在我们从
dir
列表中注意到
context
被列出,并且它也被列在
help
列表中命名的包中。因此,我应该能够访问它而无需进一步导入,并且我可以:

>>> multiprocessing.context
<module 'multiprocessing.context' from 'C:\\Program Files\\Python38\\lib\\multiprocessing\\context.py'>
最终,文档应该告诉您需要导入什么,如果只是通过演示示例。

>>> multiprocessing.context
<module 'multiprocessing.context' from 'C:\\Program Files\\Python38\\lib\\multiprocessing\\context.py'>
>>> from multiprocessing.pool import Pool
>>> from multiprocessing.dummy import Pool
>>>