Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change order of search path to fix inconsistency between pylint and astroid. #2589

Merged
merged 8 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ What's New in astroid 3.3.6?
============================
Release date: TBA

* Fix precedence of `path` arg in `modpath_from_file_with_callback` to be higher than `sys.path`


What's New in astroid 3.3.5?
Expand Down
2 changes: 1 addition & 1 deletion astroid/modutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def modpath_from_file_with_callback(
filename = os.path.expanduser(_path_from_filename(filename))
paths_to_check = sys.path.copy()
if path:
paths_to_check += path
paths_to_check = path + paths_to_check
for pathname in itertools.chain(
paths_to_check, map(_cache_normalize_path, paths_to_check)
):
Expand Down
26 changes: 26 additions & 0 deletions astroid/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

from __future__ import annotations

import contextlib
import sys
import warnings
from collections.abc import Iterator, Sequence
from typing import TYPE_CHECKING, Any, Final, Literal

from astroid.exceptions import InferenceError
Expand Down Expand Up @@ -157,3 +160,26 @@ def safe_infer(
return None # there is some kind of ambiguity
except StopIteration:
return value


def _augment_sys_path(additional_paths: Sequence[str]) -> list[str]:
original = list(sys.path)
changes = []
seen = set()
for additional_path in additional_paths:
if additional_path not in seen:
changes.append(additional_path)
seen.add(additional_path)

sys.path[:] = changes + sys.path
return original


@contextlib.contextmanager
def augmented_sys_path(additional_paths: Sequence[str]) -> Iterator[None]:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do a follow up where we move this into the test directory. By putting it here we add it to our global API, whereas it is only used in tests and we don't want to have to keep supporting it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. I saw that it is public for pylint and followed that option. However, what you are saying makes sense. Another option is to mark it private by pretending it with _. That would then be available for other modules in astroid. Open to either one.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the experience I had with deprecating stuff with astroid and pylint 2.x I'd say move it to tests. If we ever need it we can always move it :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good! Will change.

"""Augment 'sys.path' by adding entries from additional_paths."""
original = _augment_sys_path(additional_paths)
try:
yield
finally:
sys.path[:] = original
32 changes: 32 additions & 0 deletions tests/test_modutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from astroid import modutils
from astroid.const import PY310_PLUS
from astroid.interpreter._import import spec
from astroid.util import augmented_sys_path

from . import resources

Expand Down Expand Up @@ -175,6 +176,37 @@ def test_import_symlink_with_source_outside_of_path(self) -> None:
finally:
os.remove(linked_file_name)

def test_modpath_from_file_path_order(self) -> None:
"""Test for ordering of paths.
The test does the following:
1. Add a tmp directory to beginning of sys.path via augmented_sys_path
2. Create a module file in sub directory of tmp directory
3. If the sub directory is passed as additional directory, module name
should be relative to the subdirectory since additional directory has
higher precedence."""
with tempfile.TemporaryDirectory() as tmp_dir:
with augmented_sys_path([tmp_dir]):
mod_name = "module"
sub_dirname = "subdir"
sub_dir = tmp_dir + "/" + sub_dirname
os.mkdir(sub_dir)
module_file = f"{sub_dir}/{mod_name}.py"

with open(module_file, "w+", encoding="utf-8"):
pass

# Without additional directory, return relative to tmp_dir
self.assertEqual(
modutils.modpath_from_file(module_file), [sub_dirname, mod_name]
)

# With sub directory as additional directory, return relative to
# sub directory
self.assertEqual(
modutils.modpath_from_file(f"{sub_dir}/{mod_name}.py", [sub_dir]),
[mod_name],
)

def test_import_symlink_both_outside_of_path(self) -> None:
with tempfile.NamedTemporaryFile() as tmpfile:
linked_file_name = os.path.join(tempfile.gettempdir(), "symlinked_file.py")
Expand Down
Loading