Skip to content

Fix crash with NamedTuple classmethod #3323

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 1 commit into from
May 4, 2017
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
6 changes: 6 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,12 @@ def analyze_namedtuple_classdef(self, defn: ClassDef) -> bool:
items, types, default_items = self.check_namedtuple_classdef(defn)
node.node = self.build_namedtuple_typeinfo(
defn.name, items, types, default_items)
# We only really need the assignments in the body to be type checked later;
# attempting to type check methods may lead to crashes because NamedTuples
# do not have a fully functional TypeInfo.
# TODO remove this hack and add full support for NamedTuple methods
defn.defs.body = [stmt for stmt in defn.defs.body
Copy link
Member Author

Choose a reason for hiding this comment

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

This is safe because statements within a NamedTuple class fall in three groups (see check_namedtuple_classdef below):

  1. assignments, which we still type check
  2. pass and Ellipsis, which don't do anything and which we ignore here
  3. Other statements, which produce an error on line 841/847 below and now are ignored here.

if isinstance(stmt, AssignmentStmt)]
return True
return False

Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-class-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,15 @@ Y(y=1, x='1').method()
class CallsBaseInit(X):
def __init__(self, x: str) -> None:
super().__init__(x)

[case testNewNamedTupleClassMethod]
from typing import NamedTuple

class HasClassMethod(NamedTuple):
x: str

@classmethod # E: Invalid statement in NamedTuple definition; expected "field_name: field_type"
def new(cls, f: str) -> 'HasClassMethod':
pass

[builtins fixtures/classmethod.pyi]
4 changes: 4 additions & 0 deletions test-data/unit/fixtures/classmethod.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import typing

_T = typing.TypeVar('_T')

class object:
def __init__(self) -> None: pass

Expand All @@ -20,3 +22,5 @@ class int:
class str: pass
class bytes: pass
class bool: pass

class tuple(typing.Generic[_T]): pass