Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading