繁体   English   中英

当一个模块被导入两次时会发生什么?

[英]What happens when a module is imported twice?

我有一个疑问,我想得到澄清。

考虑以下名为ex_1.py的模块:

print("Hello, I'm ex_1")
def greet(name):
 print("Hello, "+name+" nice to meet you! ")

现在考虑另一个名为1_client_ex_1.py的文件,它将导入ex_1.py模块。

import ex_1.py

现在当我执行这个文件时,我得到 output 为:

Hello, I'm ex_1

正如预期的那样。

但是当我将1_client_ex_1.py更改为:

import ex_1.py
import ex_1.py

并执行它,它仍然只打印Hello, I'm ex_1一次。 它不应该打印两次吗?

没有,如果模块已经导入,则不会再次加载。

您将简单地获得对已导入模块的引用(它将来自sys.modules )。

要获取已导入模块的列表,可以查找sys.modules.keys() (注意这里的urllib导入了很多其他模块):

>>> import sys
>>> print len(sys.modules.keys())
44
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'virtualenvwrapper', '_osx_support', 'codecs', 'readline', 'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
>>> import urllib
>>> print len(sys.modules.keys())
70
>>> print sys.modules.keys()
['cStringIO', 'heapq', 'base64', 'copy_reg', 'sre_compile', '_collections', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'sysconfig', 'thread', '_ssl', '__main__', 'operator', 'encodings.encodings', '_heapq', 'abc', 'posixpath', '_weakrefset', 'errno', '_socket', 'binascii', 'encodings.codecs', 'urllib', 'sre_constants', 're', '_abcoll', 'collections', 'types', '_codecs', 'encodings.__builtin__', '_struct', '_warnings', '_scproxy', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'string', 'warnings', 'UserDict', 'struct', 'encodings.utf_8', 'textwrap', 'sys', 'ssl', 'virtualenvwrapper', '_osx_support', 'codecs', 'readline', 'os.path', 'strop', '_functools', 'sitecustomize', 'socket', 'keyword', 'signal', 'traceback', 'urlparse', 'linecache', 'itertools', 'posix', 'encodings.aliases', 'time', 'exceptions', 'sre_parse', 'os', '_weakref']
>>> import urllib #again!
>>> print len(sys.modules.keys()) #has not loaded any additional modules
70

让我们试一试:

import sys
>>> sys.modules["foo"] = "bar"  # Let's pretend we imported a module named "foo", which is a string.
>>> print __import__("foo")
bar  # Not a module, that's my string!

如您所见,如果在sys.modules找到一个模块,您将获得对它的新引用。 就是这样。


请注意,这意味着模块应设计为在导入时不会产生副作用(例如打印内容)

在交互式会话之外重新加载模块通常也不是一个很好的做法(尽管它有其用例) - 其他答案将详细说明您将如何执行此操作。

Python 脚本只会加载一个模块一次。 要重新加载它,请使用:

reload()      # Python 2

imp.reload()  # Python 3

模块仅在第一次执行import语句时加载。 另见reload()这个问题 您可以检查sys.modules以找出已加载的模块。

关于上述答案,是的 python 不会导入它两次,它只会首先检查sys.modules 但是当我们谈论同一个库的太多导入时,这个操作可能会很昂贵。 您可以在python wiki 中查看。

你可以在这里查看我的实验截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM