简体   繁体   English

Python的“导入”如何在内部工作?

[英]How does Python's “import” work internally?

When you import a module, then reimport it again, will it get reimported/overwritten, or skipped? 导入模块时,再次重新导入,是重新导入/覆盖还是跳过? When you import module "a" and "b", but also have module "b" imported in module "a", what happens? 导入模块“a”和“b”时,还在模块“a”中导入了模块“b”,会发生什么? Is it safe to do this? 这样做安全吗? For example if that module "b" has a class instantiated in it, will you end up instantiating it twice? 例如,如果该模块“b”中有一个实例化的类,你最终会实例化它两次吗?

import loads the matching .py , .pyc or .pyo file, creates a module object, and stores it with its fully qualified ("dotted") name in the sys.modules dictionary. import加载匹配的.py.pyc.pyo文件,创建一个模块对象,并将其与sys.modules字典中的完全限定(“点”)名称一起存储。 If a second import finds the module to import in this dictionary, it will return it without loading the file again. 如果第二个import在此字典中找到要导入的模块,它将返回该模块而不再次加载该文件。

To answer your questions: 回答你的问题:

When you import a module, then reimport it again, will it get reimported/overwritten, or skipped? 导入模块时,再次重新导入,是重新导入/覆盖还是跳过?

It will get skipped. 它会被跳过。 To explicitely re-import a module, use the reload() built-in function. 要明确重新导入模块,请使用reload()内置函数。

When you import module "a" and "b", but also have module "b" imported in module "a", what happens? 导入模块“a”和“b”时,还在模块“a”中导入了模块“b”,会发生什么?

import a will load a from a.py[c] , import b will return the module sys.modules['b'] already loaded by a . import a将加载aa.py[c] import b将返回模块sys.modules['b']已经装入a

Is it safe to do this? 这样做安全吗?

Yes, absolutely. 是的,一点没错。

For example if that module "b" has a class instantiated in it, will you end up instantiating it twice? 例如,如果该模块“b”中有一个实例化的类,你最终会实例化它两次吗?

Nope. 不。

The module will only be instantiated once. 该模块仅实例化一次。 It is safe to import the same module in multiple other modules. 在多个其他模块中导入相同的模块是安全的。 If there is a class instance (object) that is created in the module itself, the very same object will be accessed from all modules that import it. 如果在模块本身中创建了一个类实例(对象),则将从导入它的所有模块访问同一个对象。

You can, if you like, have a look at all imported modules: 如果您愿意,可以查看所有导入的模块:

import sys
print sys.modules

sys.modules is dictionary which maps module names the module objects. sys.modules是将模块名称映射到模块对象的字典。 The first thing the import statement does is looking in sys.modules , if it cannot find the module there, it will be instantiated, and added to sys.modules for future imports. import语句的第一件事是查看sys.modules ,如果找不到那里的模块,它将被实例化,并添加到sys.modules以供将来导入。

See this page for more details: http://effbot.org/zone/import-confusion.htm (see "What Does Python Do to Import a Module?") 有关更多详细信息,请参阅此页面: http//effbot.org/zone/import-confusion.htm (请参阅“Python导入模块的作用是什么?”)

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

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