8000 Support classes with @overload-ed __init__. · python/mypy@b9dcb7c · GitHub
[go: up one dir, main page]

Skip to content

Commit b9dcb7c

Browse files
author
Guido van Rossum
committed
Support classes with @overload-ed __init__.
1 parent f596dc6 commit b9dcb7c

File tree

3 files changed

+32
-5
lines changed

3 files changed

+32
-5
lines changed

mypy/checkexpr.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -304,12 +304,19 @@ def analyze_type_type_callee(self, item: Type, context: Context) -> Type:
304304
# but better than AnyType...), but replace the return type
305305
# with typevar.
306306
callee = self.analyze_type_type_callee(item.upper_bound, context)
307-
if not isinstance(callee, CallableType):
308-
# Might be a union.
309-
# XXX What to do for Overloaded?
307+
if isinstance(callee, CallableType):
308+
if callee.is_generic():
309+
callee = None
310+
else:
311+
callee = callee.copy_modified(ret_type=item)
312+
elif isinstance(callee, Overloaded):
313+
if callee.items()[0].is_generic():
314+
callee = None
315+
else:
316+
callee = Overloaded([c.copy_modified(ret_type=item)
317+
for c in callee.items()])
318+
if callee:
310319
return callee
311-
if not callee.is_generic():
312-
return callee.copy_modified(ret_type=item)
313320

314321
self.msg.unsupported_type_type(item, context)
315322
return AnyType()

mypy/constraints.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,9 @@ def visit_overloaded(self, template: Overloaded) -> List[Constraint]:
357357
def visit_type_type(self, template: TypeType) -> List[Constraint]:
358358
if isinstance(self.actual, CallableType) and self.actual.is_type_obj():
359359
return infer_constraints(template.item, self.actual.ret_type, self.direction)
360+
elif isinstance(self.actual, Overloaded) and self.actual.is_type_obj():
361+
return infer_constraints(template.item, self.actual.items()[0].ret_type,
362+
self.direction)
360363
elif isinstance(self.actual, TypeType):
361364
return infer_constraints(template.item, self.actual.item, self.direction)
362365
else:

mypy/test/data/check-classes.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1607,3 +1607,20 @@ def foo(arg: Type[Tuple[int]]): # E: Unsupported type Type["Tuple[int]"]
16071607
[builtins fixtures/tuple.py]
16081608
[out]
16091609
main: note: In function "foo":
1610+
1611+
[case testTypeUsingTypeCOverloadedClass]
1612+
from typing import Type, TypeVar, overload
1613+
class User:
1614+
@overload
1615+
def __init__(self) -> None: pass
1616+
@overload
1617+
def __init__(self, arg: int) -> None: pass
1618+
@classmethod
1619+
def foo(cls) -> None: pass
1620+
U = TypeVar('U', bound=User)
1621+
def new(uc: Type[U]) -> U:
1622+
uc.foo()
1623+
return uc()
1624+
u = new(User)
1625+
[builtins fixtures/classmethod.py]
1626+
[out]

0 commit comments

Comments
 (0)
0