Python Modules, Packages and Environments · Lesson 113 of 149

Python How Python Finds Modules

What you will learn

  • What sys.path is and what it contains
  • The order of the search, and shadowing
  • Ways to add folders: PYTHONPATH, sys.path, installing
  • Finding where a module comes from with __file__ and find_spec
  • A checklist for ModuleNotFoundError

1. The search path

When you write import mylib, Python does not search your whole computer. It goes through a list of folders, in order, looking for mylib.py (or a package folder mylib/). The list is sys.path:

import sys

print(sys.path[0].endswith("app"))
print(len(sys.path) > 3)
True
True

(Run from a script in a folder called app.) The real list differs on each computer, so print sys.path yourself to see it. It usually holds, in this order:

Position What it is
1st the folder of the script you ran (or the current folder for python -c and -m)
next folders from the PYTHONPATH environment variable, if set
next the standard library folders (where json, os, pathlib live)
last site-packages, where third-party packages are installed (lesson 16.6)

Python takes the first match and stops. Built-in modules (some, such as sys, are compiled into Python itself) are found before the path is searched.

Quick check: if `random.py` exists in your script's folder and also in the standard library, which is imported?

Yours. The script's folder is first on sys.path, so the first match wins.

2. Where did that module come from?

A module's __file__ attribute tells you which file was loaded:

import json, math

print(json.__file__.replace("\\", "/").split("/")[-2:])
print(getattr(math, "__file__", "built-in"))
['json', '__init__.py']
built-in

json is a package (its __init__.py). math is compiled into this Python on Windows, so it has no file. On other systems, the same module may be a separate file, so the answer depends on the installation.

To ask without importing, use importlib.util.find_spec, which returns information about where Python would load a module from, or None:

import importlib.util

spec = importlib.util.find_spec("json")
print(spec.name, spec.origin.replace("\\", "/").split("/")[-2:])
print(importlib.util.find_spec("nope"))
json ['json', '__init__.py']
None

3. Shadowing

If your own file has the same name as an installed module, and its folder comes first, yours wins and the real one is hidden ("shadowed"). The folder sh/ here contains a random.py of its own (and the script use.py next to it):

# sh/random.py
print("this is MY random.py")


def randint(a, b):
    return 4
# sh/use.py
import random

print(random.__file__.replace("\\", "/").split("/")[-2:])
print(hasattr(random, "choice"))

Running use.py from that folder printed:

this is MY random.py
['sh', 'random.py']
False

random was our file, and it had no choice. A script that imports random and then fails with AttributeError: module 'random' has no attribute 'choice' is the classic sign. The remedy: rename your file, and delete the __pycache__ folder if needed. Common victims: random.py, math.py, json.py, test.py, email.py, string.py, datetime.py.

4. Adding a folder to the path

Suppose a helper module lives in a different folder from the script:

project/
├── libs/
│   └── mylib.py        (NAME = "from libs")
└── app/
    └── main.py

From app/main.py, import mylib fails, because libs/ is not on the path:

try:
    import mylib
except ModuleNotFoundError as e:
    print("not yet:", e)
not yet: No module named 'mylib'

There are several remedies, from quick to proper.

a) Change sys.path in the program

import os
import sys

sys.path.append(os.path.abspath("../libs"))
import mylib

print(mylib.NAME)
print(mylib.__file__.replace("\\", "/").split("/")[-2:])
from libs
['libs', 'mylib.py']

sys.path is an ordinary list. append adds the folder at the end (searched last); sys.path.insert(0, folder) puts it at the start (searched first; this can shadow other modules). The relative path ../libs depends on where the program is run, so using Path(__file__).parent (lesson 15.4) is more reliable. This works, but it is a patch inside the code; use it for quick scripts only.

b) PYTHONPATH

The environment variable PYTHONPATH holds extra folders for Python to search. Setting it for a single run (Linux or macOS style shown):

$ PYTHONPATH=../libs python two.py
from libs

where two.py contained import mylib and print(mylib.NAME). On Windows PowerShell, set $env:PYTHONPATH = "..\libs" first. It is fine for experiments, but easy to forget about, and it affects every Python program started from that shell.

c) Restructure or install

The proper fixes for real projects:

  • Put the modules in a package inside the project and run from the project folder (lesson 16.3): from libs import mylib, or python -m app.main.
  • Install your project into the environment (an "editable" install, lesson 19.5), so that it is always importable.

Third-party libraries are installed with pip into site-packages (lesson 16.6) and so are always on the path of that environment.

5. Which Python? Which environment?

The path depends on which Python runs the code. A computer can have several Pythons and virtual environments (lesson 16.5), each with its own site-packages. A very common puzzle: "I installed the package, but import can't find it". The cause is usually that pip belongs to a different Python from the one running your script. Check:

import sys

print(sys.executable.replace("\\", "/").split("/")[-1])
print([p.replace("\\", "/").split("/")[-1] for p in sys.path if "site-packages" in p])
print(sys.prefix == sys.base_prefix)
python.exe
['site-packages']
False
  • sys.executable is the Python program that is running.
  • sys.prefix == sys.base_prefix is False inside a virtual environment, True outside. (These lessons were run inside the project's virtual environment, hence False.)
  • Installing with python -m pip install name guarantees that the package goes to that Python.

6. A checklist for ModuleNotFoundError

When import xyz fails:

  1. Spelling. The names are case-sensitive (import Math fails).
  2. Is it a standard module? Then check your Python version.
  3. Is it a third-party package? Install it into the same Python (lesson 16.6). Note that the install name can differ from the import name (for example, the package beautifulsoup4 is imported as bs4).
  4. Is it your own module? Is the file in the script's folder, or on the path? Does the folder have an __init__.py if it is a package?
  5. Are you in the right folder? Run from the project folder.
  6. Is something shadowing it? Look at module.__file__.
  7. Right environment? Print sys.executable.

Worked example: a "where does this import come from" tool

where(name) reports where Python would load a module from, without importing it. The folder sh/ contains a hidden random.py and a libs/mylib.py. Run from sh/.

import importlib.util
import sys
from pathlib import Path


def where(name):
    spec = importlib.util.find_spec(name)
    if spec is None:
        return f"{name}: not found on sys.path"
    if spec.origin in (None, "built-in", "frozen"):
        return f"{name}: built into Python"
    folder = Path(spec.origin).parent.name
    return f"{name}: {Path(spec.origin).name} in folder '{folder}'"


for n in ["math", "json", "mylib", "nope", "random"]:
    print(where(n))

sys.path.insert(0, str(Path("libs").resolve()))
print(where("mylib"))
print(sys.path[0] == str(Path("libs").resolve()))
math: built into Python
json: __init__.py in folder 'json'
mylib: not found on sys.path
nope: not found on sys.path
random: random.py in folder 'sh'
mylib: mylib.py in folder 'libs'
True
Line What it tells you
math built in no file; on other systems it might be a file
json in folder json a package from the standard library
mylib not found, then found before sys.path.insert, libs/ was not searched; after it, it is
random in folder sh shadowed by the local file: the standard random is hidden
nope not found find_spec returns None, so where can answer without raising an error

The folder names are from this demonstration. If your own program ever seems to import "the wrong thing", this check is the quickest way to find out why.

Common mistakes

  • Shadowing a standard module with a file of the same name.
  • Installing with the wrong pip.
  • Editing sys.path in many places, making imports depend on run order.
  • Depending on the current folder instead of the script's folder.
  • Forgetting __init__.py or running from the wrong folder.
  • Assuming the import name equals the install name.
  • Leaving a stale __pycache__ after renaming files (delete it if behaviour looks odd).

Key takeaways

  • Python searches the folders of sys.path in order and uses the first match.
  • The order: the script's folder, PYTHONPATH, the standard library, site-packages.
  • A local file with a standard module's name shadows the real one.
  • Use module.__file__ and importlib.util.find_spec(name) to see where an import comes from.
  • Fix path problems by structuring the project as a package or installing it; sys.path and PYTHONPATH are quick patches.
  • Install packages with python -m pip so they go to the Python you run.

Practice

1. What is sys.path?

Show answer

A list of folders Python searches, in order, to find modules.

2. Which folder is searched first when you run python app/main.py?

Show answer

The folder of the script, app/.

3. How can you find out which file import random loaded?

Show answer

print(random.__file__) after the import, or importlib.util.find_spec("random").origin without importing.

4. Why does AttributeError: module 'random' has no attribute 'choice' suggest shadowing?

Show answer

The real random has choice; if it is missing, a different random.py (often your own file) was imported.

5. What is the difference between sys.path.append(p) and sys.path.insert(0, p)?

Show answer

append puts the folder last (searched last); insert(0, p) puts it first (searched first, so its modules win).

6. You installed a package but import fails. What is the likely cause, and the safest install command?

Show answer

pip installed it for a different Python than the one running your script. Use python -m pip install name with the same Python.