Skip to content

declearn.test_utils.make_importable

Context manager to perform relative/local imports.

This functions establishes a context in which a given directory is added to the sys.path variable, enabling one to import the python code files it contains even without __init__.py files.

The default usage is to import from the local folder ("."); in a test or script file launched from its own directory:

with make_importable(): import local_file

It is however possible to specify another directory, and/or to use an explicit path, including the one relative to the script file:

with make_importable(os.path.dirname(file)): import local_file

Source code in declearn/test_utils/_imports.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@contextmanager
def make_importable(dirname: str = ".") -> Iterator[None]:
    """Context manager to perform relative/local imports.

    This functions establishes a context in which a given directory
    is added to the `sys.path` variable, enabling one to import the
    python code files it contains even without `__init__.py` files.

    The default usage is to import from the local folder ("."); in
    a test or script file launched from its own directory:
    >>> with make_importable():
    >>>     import local_file

    It is however possible to specify another directory, and/or to
    use an explicit path, including the one relative to the script
    file:
    >>> with make_importable(os.path.dirname(__file__)):
    >>>     import local_file
    """
    remove = False
    try:
        if dirname not in sys.path:
            sys.path.append(dirname)
            remove = True
        yield None
    finally:
        if remove:
            sys.path.remove(dirname)