sys.path.append which main.py will be imported

Question:

If I have a project with two files main.py and main2.py. In main2.py I do import sys; sys.path.append(path), and I do import main, which main.py will be imported? The one in my project or the one in path (the question poses itself only if there are two main.py obviously)?

Can I force Python to import a specific one?

Answers:

The one that is in your project.

According to python docs, the import order is:

  1. Built-in python modules. You can see the list in the variable sys.modules
  2. The sys.path entries
  3. The installation-dependent default locations

Your added directory to sys.path, so it depends on the order of entries in sys.path.

You can check the order of imports by running this code:

import sys
print(sys.path)

As you will observe, the first entry of sys.path is your module’s directory ("project directory") and the last is the one you appended.

You can force python to use the outer directory by adding it in the beginning of your sys.path:

sys.path.insert(0,path)

Although I would recommend against having same names for the modules as it is often hard to manage.

Another thing to keep in mind is that you can’t import relative paths to your sys.path. Check this answer for more information on how to work around that: https://stackoverflow.com/a/35259170/6599912

Answered By: dc914337

When two paths contain the same module name, using sys.path.append(path) isn’t going to change the priority of the imports, since append puts path at the end of the python path list

I’d use

sys.path.insert(0,path)

so modules from path come first

Example: my module foo.py imports main and there’s one main.py in the same directory and one main.py in the sub directory

foo.py
main.py
sub/main.py

in foo.py if I do:

import sys
sys.path.append("sub")
import main

print(main.__file__)

I get the main.py file path of the current directory because sys.path always starts by the main script directory.

So I could remove that directory from sys.path but it’s a bad idea because I could need other modules from there.

Now if I use insert instead:

import sys
sys.path.insert(0,"sub")
import main

print(main.__file__)

I get sub/main.py as sub is the first directory python looks into when searching modules.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.