Skip to content

Commit b39eb0f

Browse files
committed
Fixes python#1727: constructor after classmethod counts
Constructor defined after classmethod was considered to have no args in the classmethod. This commit fixes that bug.
1 parent 7f29b73 commit b39eb0f

3 files changed

Lines changed: 31 additions & 19 deletions

File tree

‎mypy/plugins/dataclasses.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -88,23 +88,6 @@ def transform(self) -> None:
8888
args=[attr.to_argument(info) for attr in attributes if attr.is_in_init],
8989
return_type=NoneTyp(),
9090
)
91-
for stmt in self._ctx.cls.defs.body:
92-
# Fix up the types of classmethods since, by default,
93-
# they will be based on the parent class' init.
94-
if isinstance(stmt, Decorator) and stmt.func.is_class:
95-
func_type = stmt.func.type
96-
if isinstance(func_type, CallableType):
97-
func_type.arg_types[0] = self._ctx.api.class_type(self._ctx.cls.info)
98-
if isinstance(stmt, OverloadedFuncDef) and stmt.is_class:
99-
func_type = stmt.type
100-
if isinstance(func_type, Overloaded):
101-
class_type = ctx.api.class_type(ctx.cls.info)
102-
for item in func_type.items():
103-
item.arg_types[0] = class_type
104-
if stmt.impl is not None:
105-
assert isinstance(stmt.impl, Decorator)
106-
if isinstance(stmt.impl.func.type, CallableType):
107-
stmt.impl.func.type.arg_types[0] = class_type
10891

10992
# Add an eq method, but only if the class doesn't already have one.
11093
if decorator_arguments['eq'] and info.get('__eq__') is None:

‎mypy/semanal.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,10 @@ class SemanticAnalyzerPass2(NodeVisitor[None],
214214
# postpone_nested_functions_stack[-1] == FUNCTION_FIRST_PHASE_POSTPONE_SECOND.
215215
postponed_functions_stack = None # type: List[List[Node]]
216216

217+
# Classmethod definitions that couldn't be prepared yet
218+
# until the class analysis is complete
219+
postponed_classmethods_stack = None # type: List[List[FuncDef]]
220+
217221
loop_depth = 0 # Depth of breakable loops
218222
cur_mod_id = '' # Current module id (or None) (phase 2)
219223
is_stub_file = False # Are we analyzing a stub file?
@@ -246,6 +250,7 @@ def __init__(self,
246250
self.missing_modules = missing_modules
247251
self.postpone_nested_functions_stack = [FUNCTION_BOTH_PHASES]
248252
self.postponed_functions_stack = []
253+
self.postponed_classmethods_stack = []
249254
self.all_exports = set() # type: Set[str]
250255
self.plugin = plugin
251256
# If True, process function definitions. If False, don't. This is used
@@ -456,6 +461,15 @@ def _visit_func_def(self, defn: FuncDef) -> None:
456461
assert ret_type is not None, "Internal error: typing.Coroutine not found"
457462
defn.type = defn.type.copy_modified(ret_type=ret_type)
458463

464+
def prepare_postponed_classmethods_signature(self) -> None:
465+
for func in self.postponed_classmethods_stack[-1]:
466+
functype = func.type
467+
assert self.type
468+
assert functype
469+
assert isinstance(functype, CallableType)
470+
leading_type = self.class_type(self.type)
471+
func.type = replace_implicit_first_type(functype, leading_type)
472+
459473
def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None:
460474
"""Check basic signature validity and tweak annotation of self/cls argument."""
461475
# Only non-static methods are special.
@@ -467,10 +481,10 @@ def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None:
467481
self_type = functype.arg_types[0]
468482
if isinstance(self_type, AnyType):
469483
if func.is_class or func.name() in ('__new__', '__init_subclass__'):
470-
leading_type = self.class_type(info)
484+
self.postponed_classmethods_stack[-1].append(func)
471485
else:
472486
leading_type = fill_typevars(info)
473-
func.type = replace_implicit_first_type(functype, leading_type)
487+
func.type = replace_implicit_first_type(functype, leading_type)
474488

475489
def set_original_def(self, previous: Optional[Node], new: FuncDef) -> bool:
476490
"""If 'new' conditionally redefine 'previous', set 'previous' as original
@@ -834,13 +848,16 @@ def enter_class(self, info: TypeInfo) -> None:
834848
self.locals.append(None) # Add class scope
835849
self.block_depth.append(-1) # The class body increments this to 0
836850
self.postpone_nested_functions_stack.append(FUNCTION_BOTH_PHASES)
851+
self.postponed_classmethods_stack.append([])
837852
self.type = info
838853

839854
def leave_class(self) -> None:
840855
""" Restore analyzer state. """
841856
self.postpone_nested_functions_stack.pop()
842857
self.block_depth.pop()
843858
self.locals.pop()
859+
self.prepare_postponed_classmethods_signature()
860+
self.postponed_classmethods_stack.pop()
844861
self.type = self.type_stack.pop()
845862

846863
def analyze_class_decorator(self, defn: ClassDef, decorator: Expression) -> None:

‎test-data/unit/check-classes.test‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,18 @@ main:3: error: Incompatible types in assignment (expression has type "B", variab
616616
main:4: error: Incompatible types in assignment (expression has type "A", variable has type "D")
617617
main:5: error: Incompatible types in assignment (expression has type "D2", variable has type "D")
618618

619+
[case testClassmethodBeforeInit]
620+
class C:
621+
@classmethod
622+
def create(cls, arg: int) -> 'C':
623+
return cls(arg)
624+
625+
def __init__(self, arg: 'int') -> None:
626+
self._arg: int = arg
627+
628+
reveal_type(C.create) # E: Revealed type is 'def (arg: builtins.int) -> __main__.C'
629+
[builtins fixtures/classmethod.pyi]
630+
619631

620632
-- Attribute access in class body
621633
-- ------------------------------

0 commit comments

Comments
 (0)