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

Suggest using upper bound for unbound tvar #13730

Merged
merged 3 commits into from
Sep 26, 2022
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
16 changes: 13 additions & 3 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,13 +1231,23 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: str | None) ->

def check_unbound_return_typevar(self, typ: CallableType) -> None:
"""Fails when the return typevar is not defined in arguments."""
if typ.ret_type in typ.variables:
arg_type_visitor = CollectArgTypes()
if isinstance(typ.ret_type, TypeVarType) and typ.ret_type in typ.variables:
arg_type_visitor = CollectArgTypeVarTypes()
for argtype in typ.arg_types:
argtype.accept(arg_type_visitor)

if typ.ret_type not in arg_type_visitor.arg_types:
self.fail(message_registry.UNBOUND_TYPEVAR, typ.ret_type, code=TYPE_VAR)
upper_bound = get_proper_type(typ.ret_type.upper_bound)
if not (
isinstance(upper_bound, Instance)
and upper_bound.type.fullname == "builtins.object"
):
self.note(
"Consider using the upper bound "
f"{format_type(typ.ret_type.upper_bound)} instead",
context=typ.ret_type,
)

def check_default_args(self, item: FuncItem, body_is_trivial: bool) -> None:
for arg in item.arguments:
Expand Down Expand Up @@ -6375,7 +6385,7 @@ def has_valid_attribute(self, typ: Type, name: str) -> bool:
return not watcher.has_new_errors()


class CollectArgTypes(TypeTraverserVisitor):
class CollectArgTypeVarTypes(TypeTraverserVisitor):
"""Collects the non-nested argument types in a set."""

def __init__(self) -> None:
Expand Down
1 change: 1 addition & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -3233,6 +3233,7 @@ def error(u_c: Type[U]) -> P: # Error here, see below
[out]
main:11: note: Revealed type is "__main__.WizUser"
main:12: error: A function returning TypeVar should receive at least one argument containing the same TypeVar
main:12: note: Consider using the upper bound "ProUser" instead
main:13: error: Value of type variable "P" of "new_pro" cannot be "U"
main:13: error: Incompatible return value type (got "U", expected "P")

Expand Down
16 changes: 11 additions & 5 deletions test-data/unit/check-typevar-unbound.test
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@

[case testUnboundTypeVar]
from typing import TypeVar

T = TypeVar('T')

def f() -> T: # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
...

f()

U = TypeVar('U', bound=int)

def g() -> U: # E: A function returning TypeVar should receive at least one argument containing the same TypeVar \
# N: Consider using the upper bound "int" instead
...

V = TypeVar('V', int, str)

# TODO: this should also give an error
def h() -> V:
...

[case testInnerFunctionTypeVar]

Expand All @@ -21,15 +30,13 @@ def g(a: T) -> T:
...
return f()


[case testUnboundIterableOfTypeVars]
from typing import Iterable, TypeVar

T = TypeVar('T')

def f() -> Iterable[T]:
...

f()

[case testBoundTypeVar]
Expand All @@ -40,7 +47,6 @@ T = TypeVar('T')
def f(a: T, b: T, c: int) -> T:
...


[case testNestedBoundTypeVar]
from typing import Callable, List, Union, Tuple, TypeVar

Expand Down