1

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

asked May 13, 2017 at 23:29

1 Answer 1

1

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.

answered May 13, 2017 at 23:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.