Jonas M
Jonas M

Reputation: 35

How can I import a module to other scripts imported on Python?

I'm working on a project on Python where I work with different scripts. Problem here is that I don't know how I can import a module to several scripts that I've imported. For example:

#main.py
import os 
import script1
import script2

How can I import os module to all other scripts, so that I don't have to import again os on script1.py and on script2.py

Im new to Python, thanks

Upvotes: 1

Views: 70

Answers (1)

steliosbl
steliosbl

Reputation: 8921

This really isn't a good idea, as it will make it quite hard to keep track of which module (file) requires which imports. However, if you must, then it is possible to reduce the number of import statements in your files to one like so:

Create a file (say, for example, imports.py) and put all your imports in there:

import os 
import script1
import script2
# etc

Then, for each file, instead of copying all the imports you need only write this:

from imports import *

..and you will be able to use them from that file.

It is worth noting that doing this wont actually achieve much more than eliminate the need for you to write the imports at the top of each file. Python already makes sure that, during the execution of your code, each module is imported only once regardless of how many times you include the statement in your code.

According to the documentation, regarding the import process:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. [...] The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. [...] During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes.

For further clarification, user dim-an put it really well in this answer.

Upvotes: 1

Related Questions