diff --git a/_python_utils_tests/test_import.py b/_python_utils_tests/test_import.py index b8e1dea..0227034 100644 --- a/_python_utils_tests/test_import.py +++ b/_python_utils_tests/test_import.py @@ -299,3 +299,64 @@ def lookup(name: str) -> str: import_.import_global(module_name, ['eggs'], locals_={}, globals_=scope) assert scope == {} assert 'eggs' not in calls + + +@pytest.fixture +def deep_package( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> collections.abc.Iterator[str]: + """Create ``testrel.nested.deeper`` with importable helper modules.""" + package: pathlib.Path = tmp_path / 'testrel' + nested: pathlib.Path = package / 'nested' + deeper: pathlib.Path = nested / 'deeper' + deeper.mkdir(parents=True) + (package / '__init__.py').write_text('', encoding='utf-8') + (nested / '__init__.py').write_text('', encoding='utf-8') + (deeper / '__init__.py').write_text('', encoding='utf-8') + (package / 'helper.py').write_text('value = 42\n', encoding='utf-8') + (nested / 'inner.py').write_text( + "inner_value = 'inner'\n", encoding='utf-8' + ) + monkeypatch.setattr(sys, 'path', [str(tmp_path), *sys.path]) + + yield 'testrel' + + imported: list[str] = [ + name for name in sys.modules if name.split('.')[0] == 'testrel' + ] + for name in imported: + del sys.modules[name] + + +def test_import_globals_relative_import_two_dots(deep_package: str) -> None: + """Resolve ``..helper`` two levels up, to ``testrel.helper`` (#73).""" + locals_: types.Dict[str, types.Any] = {} + globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'} + import_.import_global('..helper', locals_=locals_, globals_=globals_) + assert globals_['value'] == 42 + + +def test_import_globals_relative_import_three_dots(deep_package: str) -> None: + """Resolve ``...helper`` three levels up, to ``testrel.helper`` (#73).""" + locals_: types.Dict[str, types.Any] = {} + globals_: types.Dict[str, types.Any] = { + '__package__': 'testrel.nested.deeper' + } + import_.import_global('...helper', locals_=locals_, globals_=globals_) + assert globals_['value'] == 42 + + +def test_import_globals_relative_import_one_dot(deep_package: str) -> None: + """Keep resolving a single leading dot one level up (#73 control).""" + locals_: types.Dict[str, types.Any] = {} + globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'} + import_.import_global('.inner', locals_=locals_, globals_=globals_) + assert globals_['inner_value'] == 'inner' + + +def test_import_globals_relative_import_dots_only(deep_package: str) -> None: + """Reject a dots-only name, which names no module to import (#73).""" + locals_: types.Dict[str, types.Any] = {} + globals_: types.Dict[str, types.Any] = {'__package__': 'testrel.nested'} + with pytest.raises(ImportError): + import_.import_global('..', locals_=locals_, globals_=globals_) diff --git a/python_utils/import_.py b/python_utils/import_.py index 642b4ae..5223f93 100644 --- a/python_utils/import_.py +++ b/python_utils/import_.py @@ -113,10 +113,14 @@ def import_global( # noqa: C901 globals_ = frame.f_globals try: - # Relative imports are supported (from .spam import eggs) + # Relative imports are supported (from .spam import eggs). Each + # leading dot counts as one level, so ``..spam`` goes up two. if not name_parts[0]: - name_parts = name_parts[1:] - level = 1 + dots: int = 0 + while dots < len(name_parts) and not name_parts[dots]: + dots += 1 + level = dots + name_parts = name_parts[dots:] or [''] # raise IOError((name, level)) module = __import__(