Skip to content

Support namedtuple as one of multiple superclasses #2091

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 6 commits into from
Sep 8, 2016
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
13 changes: 5 additions & 8 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,20 +163,17 @@ def visit_callable_type(self, left: CallableType) -> bool:
def visit_tuple_type(self, left: TupleType) -> bool:
right = self.right
if isinstance(right, Instance):
if is_named_instance(right, 'builtins.object'):
if is_named_instance(right, 'typing.Sized'):
return True
if is_named_instance(right, 'builtins.tuple'):
target_item_type = right.args[0]
return all(is_subtype(item, target_item_type)
for item in left.items)
elif is_named_instance(right, 'typing.Sized'):
return True
elif (is_named_instance(right, 'typing.Iterable') or
elif (is_named_instance(right, 'builtins.tuple') or
is_named_instance(right, 'typing.Iterable') or
is_named_instance(right, 'typing.Container') or
is_named_instance(right, 'typing.Sequence') or
is_named_instance(right, 'typing.Reversible')):
iter_type = right.args[0]
return all(is_subtype(li, iter_type) for li in left.items)
elif is_subtype(left.fallback, right, self.check_type_parameter):
return True
return False
elif isinstance(right, TupleType):
if len(left.items) != len(right.items):
Expand Down
22 changes: 21 additions & 1 deletion test-data/unit/check-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -318,4 +318,24 @@ reveal_type(X._field_types) # E: Revealed type is 'builtins.dict[builtins.str,
x = None # type: X
reveal_type(x._field_types) # E: Revealed type is 'builtins.dict[builtins.str, Any]'

[builtins fixtures/dict.pyi]
[builtins fixtures/dict.pyi]

[case testNamedTupleAndOtherSuperclass]
from typing import NamedTuple

class A: pass
def f(x: A) -> None: pass

class B(NamedTuple('B', []), A): pass
f(B())
x = None # type: A
x = B()

# Sanity check: fail if baseclass does not match
class C: pass
def g(x: C) -> None: pass
class D(NamedTuple('D', []), A): pass

g(D()) # E: Argument 1 to "g" has incompatible type "D"; expected "C"
y = None # type: C
y = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")