Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when import modules in python?

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.

like image 414
Deniz Avatar asked Oct 29 '12 19:10

Deniz


People also ask

Does importing a module execute it?

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.

What happens when you import a class in Python?

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.

What is the use of from module import?

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.

When a module is imported for first time then?

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.


1 Answers

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.

like image 178
Lukas Graf Avatar answered Oct 01 '22 21:10

Lukas Graf