sys.path.append which will be imported

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

Can I force Python to import a specific one?

>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

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:


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:

Leave a Reply