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

Improve brain for typing.Callable + typing.Type #1192

Merged
merged 2 commits into from
Sep 29, 2021
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
2 changes: 2 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ Release date: TBA

* Astroid does not trigger it's own deprecation warning anymore.

* Improve brain for ``typing.Callable`` and ``typing.Type``.


What's New in astroid 2.8.0?
============================
Expand Down
47 changes: 33 additions & 14 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ def _looks_like_typing_alias(node: Call) -> bool:
and node.func.name == "_alias"
and (
# _alias function works also for builtins object such as list and dict
isinstance(node.args[0], Attribute)
or isinstance(node.args[0], Name)
and node.args[0].name != "type"
Copy link
Member Author

Choose a reason for hiding this comment

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

Noticed that type was excluded as well. This was originally added with #921, I couldn't however find a good reason to keep it that way. It works as expected even for type. Could be that the type brain improved since then, idk.

I did run the acceptance test that caused headaches a while back. Worked without problems.

pytest -m acceptance -k "test_libmodule[typing.py]"

isinstance(node.args[0], (Attribute, Name))
)
)

Expand Down Expand Up @@ -280,7 +278,7 @@ def infer_typing_alias(
or not len(node.parent.targets) == 1
or not isinstance(node.parent.targets[0], AssignName)
):
return None
raise UseInferenceDefault
try:
res = next(node.args[0].infer(context=ctx))
except StopIteration as e:
Expand Down Expand Up @@ -318,37 +316,58 @@ def infer_typing_alias(
return iter([class_def])


def _looks_like_tuple_alias(node: Call) -> bool:
"""Return True if call is for Tuple alias.
def _looks_like_special_alias(node: Call) -> bool:
"""Return True if call is for Tuple or Callable alias.

In PY37 and PY38 the call is to '_VariadicGenericAlias' with 'tuple' as
first argument. In PY39+ it is replaced by a call to '_TupleType'.

PY37: Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
PY39: Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')


PY37: Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
PY39: Callable = _CallableType(collections.abc.Callable, 2)
"""
return isinstance(node.func, Name) and (
not PY39_PLUS
and node.func.name == "_VariadicGenericAlias"
and isinstance(node.args[0], Name)
and node.args[0].name == "tuple"
and (
isinstance(node.args[0], Name)
and node.args[0].name == "tuple"
or isinstance(node.args[0], Attribute)
and node.args[0].as_string() == "collections.abc.Callable"
)
or PY39_PLUS
and node.func.name == "_TupleType"
and isinstance(node.args[0], Name)
and node.args[0].name == "tuple"
and (
node.func.name == "_TupleType"
and isinstance(node.args[0], Name)
and node.args[0].name == "tuple"
or node.func.name == "_CallableType"
and isinstance(node.args[0], Attribute)
and node.args[0].as_string() == "collections.abc.Callable"
)
)


def infer_tuple_alias(
def infer_special_alias(
node: Call, ctx: context.InferenceContext = None
) -> typing.Iterator[ClassDef]:
"""Infer call to tuple alias as new subscriptable class typing.Tuple."""
if not (
isinstance(node.parent, Assign)
and len(node.parent.targets) == 1
and isinstance(node.parent.targets[0], AssignName)
):
raise UseInferenceDefault
try:
res = next(node.args[0].infer(context=ctx))
except StopIteration as e:
raise InferenceError(node=node.args[0], context=context) from e

assign_name = node.parent.targets[0]
class_def = ClassDef(
name="Tuple",
name=assign_name.name,
parent=node.parent,
)
class_def.postinit(bases=[res], body=[], decorators=None)
Expand Down Expand Up @@ -413,5 +432,5 @@ def infer_typing_cast(
Call, inference_tip(infer_typing_alias), _looks_like_typing_alias
)
AstroidManager().register_transform(
Call, inference_tip(infer_tuple_alias), _looks_like_tuple_alias
Call, inference_tip(infer_special_alias), _looks_like_special_alias
)
30 changes: 28 additions & 2 deletions tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1677,6 +1677,19 @@ def test_tuple_type(self):
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef)
assert inferred.qname() == "typing.Tuple"

@test_utils.require_version(minver="3.7")
def test_callable_type(self):
node = builder.extract_node(
"""
from typing import Callable, Any
Callable[..., Any]
"""
)
inferred = next(node.infer())
assert isinstance(inferred, nodes.ClassDef)
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef)
assert inferred.qname() == "typing.Callable"

@test_utils.require_version(minver="3.7")
def test_typing_generic_subscriptable(self):
"""Test typing.Generic is subscriptable with __class_getitem__ (added in PY37)"""
Expand Down Expand Up @@ -1933,8 +1946,7 @@ def test_typing_object_builtin_subscriptable(self):
"""
Test that builtins alias, such as typing.List, are subscriptable
"""
# Do not test Tuple as it is inferred as _TupleType class (needs a brain?)
for typename in ("List", "Dict", "Set", "FrozenSet"):
for typename in ("List", "Dict", "Set", "FrozenSet", "Tuple"):
src = f"""
import typing
typing.{typename:s}[int]
Expand All @@ -1944,6 +1956,20 @@ def test_typing_object_builtin_subscriptable(self):
self.assertIsInstance(inferred, nodes.ClassDef)
self.assertIsInstance(inferred.getattr("__iter__")[0], nodes.FunctionDef)

@staticmethod
@test_utils.require_version(minver="3.9")
def test_typing_type_subscriptable():
node = builder.extract_node(
"""
from typing import Type
Type[int]
"""
)
inferred = next(node.infer())
assert isinstance(inferred, nodes.ClassDef)
assert isinstance(inferred.getattr("__class_getitem__")[0], nodes.FunctionDef)
assert inferred.qname() == "typing.Type"

def test_typing_cast(self) -> None:
node = builder.extract_node(
"""
Expand Down