Skip to content

Commit 7d26dcf

Browse files
Fix incorrect preferred-modules matches (#8481)
Co-authored-by: d33bs <[email protected]> (cherry picked from commit d64c0cc) Co-authored-by: Daniël van Noord <[email protected]>
1 parent d6f3ae8 commit 7d26dcf

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

doc/whatsnew/fragments/8453.bugfix

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a regression of ``preferred-modules`` where a partial match was used instead of the required full match.
2+
3+
Closes #8453

pylint/checkers/imports.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -922,7 +922,15 @@ def _check_preferred_module(self, node: ImportNode, mod_path: str) -> None:
922922
mod_compare = [f"{node.modname}.{name[0]}" for name in node.names]
923923

924924
# find whether there are matches with the import vs preferred_modules keys
925-
matches = [k for k in self.preferred_modules for mod in mod_compare if k in mod]
925+
matches = [
926+
k
927+
for k in self.preferred_modules
928+
for mod in mod_compare
929+
# exact match
930+
if k == mod
931+
# checks for base module matches
932+
or k in mod.split(".")[0]
933+
]
926934

927935
# if we have matches, add message
928936
if matches:

tests/checkers/unittest_imports.py

+17
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,23 @@ def test_preferred_module(capsys: CaptureFixture[str]) -> None:
192192
# assert there were no errors
193193
assert len(errors) == 0
194194

195+
# Test for challenges with preferred modules indefinite matches
196+
Run(
197+
[
198+
f"{os.path.join(REGR_DATA, 'preferred_module/unpreferred_submodule.py')}",
199+
"-d all",
200+
"-e preferred-module",
201+
# prefer pathlib instead of random (testing to avoid regression)
202+
# pathlib shouldn't match with path, which is in the test file
203+
"--preferred-modules=random:pathlib",
204+
],
205+
exit=False,
206+
)
207+
_, errors = capsys.readouterr()
208+
209+
# Assert there were no errors
210+
assert len(errors) == 0
211+
195212
@staticmethod
196213
def test_allow_reexport_package(capsys: CaptureFixture[str]) -> None:
197214
"""Test --allow-reexport-from-package option."""

0 commit comments

Comments
 (0)