2

Which of the following describes the behavior of from [...] import [...]?

  • cwd first: look in working directory first, then the path
  • path first: look in the path, then the working directory

Consider the following scripts:

Change Path

sys.path.insert(0, 'E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
from src import name
sys.path.pop(0)

Change Cwd

old_cwd = os.getcwd()
os.chdir('E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
from src import name
os.chdir(old_cwd)

Combined Script

old_cwd = os.getcwd(); os.chdir('E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
sys.path.insert(0, 'E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')

from src import name

os.chdir(old_cwd)
sys.path.pop(0)

Suppose there something named src in both sys.path and the cwd, and that the src in the system path is not the same src in the cwd

Did we just import src from sys.path? or src from the cwd?

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • Possible duplicate of [How does python find a module file if the import statement only contains the filename?](https://stackoverflow.com/questions/15252040/how-does-python-find-a-module-file-if-the-import-statement-only-contains-the-fil) – wwii Mar 22 '18 at 00:27

1 Answers1

1

Only sys.path is used to search for files to load as modules; Python does not look at other directories outside of sys.path.¹ The current working directory will be searched only if '' (the empty string) is in the path², so if there is an src.py in both the current working directory and another directory in the path, the one that will be loaded is whichever comes first in the path.

You will find that '' appears at the front of sys.path automatically when you run the Python interpreter directly (including when you run python -m modulename). This is standard Python behaviour. However, if you run a script directly (e.g., typing just myscript where it starts with #!/usr/bin/env python) instead that script's directory (e.g., /usr/bin if your shell found and ran /usr/bin/myscript) will be added to the front of the path. (The script itself may of course add further items to the front of the path as it runs.)


¹ Actually, this is not entirely true; import queries finders in sys.meta_path first. Those can look anywhere they like and may not even use sys.path.
² You could also use ., ./. or various similar ideas in the path, though getting tricky like that is just asking for trouble.

cjs
  • 25,752
  • 9
  • 89
  • 101