Skip to content

Commit

Permalink
Fix IndexError when typing._alias() has missing arguments
Browse files Browse the repository at this point in the history
Closes #2513

(cherry picked from commit ca0230d)
  • Loading branch information
correctmost authored and github-actions[bot] committed Oct 23, 2024
1 parent 8c74a5f commit 76968f3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ What's New in astroid 3.4.0?
Release date: TBA


* Fix crash when typing._alias() call is missing arguments.

Closes #2513


What's New in astroid 3.3.6?
============================
Expand Down
1 change: 1 addition & 0 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ def _looks_like_typing_alias(node: Call) -> bool:
isinstance(node.func, Name)
# TODO: remove _DeprecatedGenericAlias when Py3.14 min
and node.func.name in {"_alias", "_DeprecatedGenericAlias"}
and len(node.args) == 2
and (
# _alias function works also for builtins object such as list and dict
isinstance(node.args[0], (Attribute, Name))
Expand Down
49 changes: 48 additions & 1 deletion tests/brain/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import pytest

from astroid import builder
from astroid import bases, builder, nodes
from astroid.exceptions import InferenceError


Expand All @@ -23,3 +23,50 @@ def test_infer_typevar() -> None:
)
with pytest.raises(InferenceError):
call_node.inferred()


class TestTypingAlias:
def test_infer_typing_alias(self) -> None:
"""
Test that _alias() calls can be inferred.
"""
node = builder.extract_node(
"""
from typing import _alias
x = _alias(int, float)
"""
)
assert isinstance(node, nodes.Assign)
assert isinstance(node.value, nodes.Call)
inferred = next(node.value.infer())
assert isinstance(inferred, nodes.ClassDef)
assert len(inferred.bases) == 1
assert inferred.bases[0].name == "int"

@pytest.mark.parametrize(
"alias_args",
[
"", # two missing arguments
"int", # one missing argument
"int, float, tuple", # one additional argument
],
)
def test_infer_typing_alias_incorrect_number_of_arguments(
self, alias_args: str
) -> None:
"""
Regression test for: https://github.com/pylint-dev/astroid/issues/2513
Test that _alias() calls with the incorrect number of arguments can be inferred.
"""
node = builder.extract_node(
f"""
from typing import _alias
x = _alias({alias_args})
"""
)
assert isinstance(node, nodes.Assign)
assert isinstance(node.value, nodes.Call)
inferred = next(node.value.infer())
assert isinstance(inferred, bases.Instance)
assert inferred.name == "_SpecialGenericAlias"

0 comments on commit 76968f3

Please sign in to comment.