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.
When you import a module in Python, all the code in it will be run, and all the variables in that module will be stuck on that module object.
Importing classes from other programs allows us to use them within the current program. Thus, helping in improved readability and reusability of code. Importing can be done within the same or from different folders. If you want to learn more about python Programming, visit Python Programming Tutorials.
from .. import statement allows you to import specific functions/variables from a module instead of importing everything. In the previous example, when you imported calculation into module_test.py , both the add() and sub() functions were imported.
A module code is evaluated only the first time when imported. If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers. The one-time evaluation has important consequences, that we should be aware of.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With