0

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
  • The list of directories to be searched for imports are defined when the interpreter starts, with the current working directory and any directories listed in the PYTHONPATH environment variable prepended to the list. Changing current working directory won't change add the new directory to the list, as Hai Vu noted in his answer. Just curious, what's the intended use of this? If you wrote the temp file to the current working directory, it should actually work, but I haven't tested it. Commented Feb 27, 2024 at 23:08

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.