`importlib.import_module` not finding module in working directory

57 Views Asked by At

I would like to import from the current working directory. For example:

import os
import pathlib
import tempfile
from importlib import import_module

with tempfile.TemporaryDirectory() as temp_dir:
    tmp_dir = pathlib.Path(temp_dir)
    (tmp_dir / "foo").mkdir()
    (tmp_dir / "foo" / "__init__.py").write_text("def bar(): pass")
    orig = os.getcwd()
    os.chdir(tmp_dir)
    print(import_module("foo"))
    os.chdir(orig)

However:

Traceback (most recent call last):
  File "/Users/tdegeus/data/prog/src/conda_envfile/t.py", line 12, in <module>
    print(import_module("foo"))
          ^^^^^^^^^^^^^^^^^^^^
  File "/Users/tdegeus/miniforge3/envs/pre/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'foo'

(It does work if the directory exists prior to execution.)

1

There are 1 best solutions below

0
Hai Vu On

My guess is the Python interpreter determines which directories should be in the "import path" before hand and os.chdir() could not change that fact. A work-around is to fix up the import path (sys.path) before importing:

import pathlib
import sys
import tempfile
from importlib import import_module

BAR = """
def bar():
    print("this is bar")
"""

with tempfile.TemporaryDirectory() as temp_dir:
    # Create the package
    tmp_dir = pathlib.Path(temp_dir)
    (tmp_dir / "foo").mkdir()
    (tmp_dir / "foo" / "__init__.py").write_text(BAR)

    # Fix up the import path and import
    sys.path.append(temp_dir)
    foo = import_module("foo")
    foo.bar()
    sys.path.remove(temp_dir)