What happens when import modules in python?

点点圈 提交于 2020-01-13 03:07:34

问题


I want to know really what happens when we import a module file in python.I mean it's process, in other words what things by python will be run or check?! like __init__.py or sys.modules and etc. for example i know __init__.py are necessary files in every package,i want to know python what does with these files on import time? please light this for me.


回答1:


Read the tutorial section about modules, the documentation of the import statement, the imp module (particularly the examples) and maybe the docs for the __import__ builtin. That should get you a long way. If you still want to know more, I'd suggest to ask a specific question, this one is a bit on the broad side.

Edit: After reading your question once more, there is a specific part to your question, about what __init__.py does in packages. It basically can be empty or contain initialization code that will be executed when that package is imported. See the section about packages for details.

In an __init__.py you could also set __all__, which defines what symbols get imported when you do from yourpackage import *. This is explained in detail in importing * from a package.



来源:https://stackoverflow.com/questions/13128114/what-happens-when-import-modules-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!