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.)
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: