-
-
Notifications
You must be signed in to change notification settings - Fork 305
Add brain module for statistics inference #2832
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html | ||
| # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE | ||
| # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt | ||
|
|
||
| """Astroid hooks for understanding statistics library module. | ||
|
|
||
| Provides inference improvements for statistics module functions that have | ||
| complex runtime behavior difficult to analyze statically. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Iterator | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from astroid.context import InferenceContext | ||
| from astroid.inference_tip import inference_tip | ||
| from astroid.manager import AstroidManager | ||
| from astroid.nodes.node_classes import Attribute, Call, ImportFrom | ||
| from astroid.util import Uninferable | ||
|
|
||
| if TYPE_CHECKING: | ||
| from astroid.typing import InferenceResult | ||
|
|
||
|
|
||
| def _looks_like_statistics_quantiles(node: Call) -> bool: | ||
| """Check if this is a call to statistics.quantiles.""" | ||
| # Case 1: statistics.quantiles(...) | ||
| if isinstance(node.func, Attribute): | ||
| if node.func.attrname != "quantiles": | ||
| return False | ||
| if hasattr(node.func, "expr") and hasattr(node.func.expr, "name"): | ||
| if node.func.expr.name == "statistics": | ||
| return True | ||
|
|
||
| # Case 2: from statistics import quantiles; quantiles(...) | ||
| if hasattr(node.func, "name") and node.func.name == "quantiles": | ||
emmanuel-ferdman marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Check if quantiles was imported from statistics | ||
| try: | ||
| frame = node.frame() | ||
| if "quantiles" in frame.locals: | ||
| # Look for import from statistics | ||
| for stmt in frame.body: | ||
| if ( | ||
| isinstance(stmt, ImportFrom) | ||
| and stmt.modname == "statistics" | ||
| and any(name[0] == "quantiles" for name in stmt.names or []) | ||
| ): | ||
| return True | ||
| except (AttributeError, TypeError): | ||
| # If we can't determine the import context, be conservative | ||
| pass | ||
|
|
||
| return False | ||
|
|
||
|
|
||
| def infer_statistics_quantiles( | ||
| node: Call, context: InferenceContext | None = None | ||
| ) -> Iterator[InferenceResult]: | ||
| """Infer the result of statistics.quantiles() calls. | ||
|
|
||
| Returns Uninferable because quantiles() has complex runtime behavior | ||
| that cannot be statically analyzed, preventing false positives in | ||
| pylint's unbalanced-tuple-unpacking checker. | ||
|
|
||
| statistics.quantiles() returns a list with (n-1) elements, but static | ||
| analysis sees only the empty list initializations in the function body. | ||
| """ | ||
| yield Uninferable | ||
|
|
||
|
|
||
| def register(manager: AstroidManager) -> None: | ||
| """Register statistics-specific inference improvements.""" | ||
| manager.register_transform( | ||
| Call, | ||
| inference_tip(infer_statistics_quantiles), | ||
| _looks_like_statistics_quantiles, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html | ||
| # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE | ||
| # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt | ||
|
|
||
| """Tests for brain statistics module.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import unittest | ||
|
|
||
| from astroid import extract_node | ||
| from astroid.util import Uninferable | ||
|
|
||
|
|
||
| class StatisticsBrainTest(unittest.TestCase): | ||
| """Test the brain statistics module functionality.""" | ||
|
|
||
| def test_statistics_quantiles_inference(self) -> None: | ||
| """Test that statistics.quantiles() returns Uninferable instead of empty list.""" | ||
| node = extract_node( | ||
| """ | ||
| import statistics | ||
| statistics.quantiles(list(range(100)), n=4) #@ | ||
| """ | ||
| ) | ||
| inferred = list(node.infer()) | ||
| self.assertEqual(len(inferred), 1) | ||
| self.assertIs(inferred[0], Uninferable) | ||
|
|
||
| def test_statistics_quantiles_different_args(self) -> None: | ||
| """Test statistics.quantiles with different arguments.""" | ||
| node = extract_node( | ||
| """ | ||
| import statistics | ||
| statistics.quantiles([1, 2, 3, 4, 5], n=10, method='inclusive') #@ | ||
| """ | ||
| ) | ||
| inferred = list(node.infer()) | ||
| self.assertEqual(len(inferred), 1) | ||
| self.assertIs(inferred[0], Uninferable) | ||
|
|
||
| def test_statistics_quantiles_assignment_unpacking(self) -> None: | ||
| """Test the specific case that was causing false positives.""" | ||
| node = extract_node( | ||
| """ | ||
| import statistics | ||
| q1, q2, q3 = statistics.quantiles(list(range(100)), n=4) #@ | ||
| """ | ||
| ) | ||
| call_node = node.value | ||
| inferred = list(call_node.infer()) | ||
| self.assertEqual(len(inferred), 1) | ||
| self.assertIs(inferred[0], Uninferable) | ||
|
|
||
| def test_other_statistics_functions_not_affected(self) -> None: | ||
| """Test that other statistics functions are not affected by our brain module.""" | ||
| node = extract_node( | ||
| """ | ||
| import statistics | ||
| statistics.mean([1, 2, 3, 4, 5]) #@ | ||
| """ | ||
| ) | ||
| inferred = list(node.infer()) | ||
| self.assertNotEqual(len(inferred), 0) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.