Skip to content

Commit 8a5f463

Browse files
gvanrossumddfisher
authored andcommitted
Fix crash for deferred methods introduced by #2193 (self-type). (#2375)
Fixes #2372.
1 parent bf3bf48 commit 8a5f463

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

mypy/checker.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
[
6666
('node', FuncItem),
6767
('context_type_name', Optional[str]), # Name of the surrounding class (for error messages)
68+
('class_type', Optional[Type]), # And its type (from class_context)
6869
])
6970

7071

@@ -202,13 +203,20 @@ def check_second_pass(self) -> bool:
202203
todo = self.deferred_nodes
203204
self.deferred_nodes = []
204205
done = set() # type: Set[FuncItem]
205-
for node, type_name in todo:
206+
for node, type_name, class_type in todo:
206207
if node in done:
207208
continue
209+
# This is useful for debugging:
210+
# print("XXX in pass %d, class %s, function %s" %
211+
# (self.pass_num, type_name, node.fullname() or node.name()))
208212
done.add(node)
209213
if type_name:
210214
self.errors.push_type(type_name)
215+
if class_type:
216+
self.class_context.append(class_type)
211217
self.accept(node)
218+
if class_type:
219+
self.class_context.pop()
212220
if type_name:
213221
self.errors.pop_type()
214222
return True
@@ -221,7 +229,11 @@ def handle_cannot_determine_type(self, name: str, context: Context) -> None:
221229
type_name = self.errors.type_name[-1]
222230
else:
223231
type_name = None
224-
self.deferred_nodes.append(DeferredNode(node, type_name))
232+
if self.class_context:
233+
class_context_top = self.class_context[-1]
234+
else:
235+
class_context_top = None
236+
self.deferred_nodes.append(DeferredNode(node, type_name, class_context_top))
225237
# Set a marker so that we won't infer additional types in this
226238
# function. Any inferred types could be bogus, because there's at
227239
# least one type that we don't know.

test-data/unit/check-modules.test

+8
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,14 @@ def deco(f: Callable[[T], int]) -> Callable[[T], int]:
12961296
main:1: note: In module imported here:
12971297
tmp/a.py:6: error: Revealed type is 'def (builtins.str*) -> builtins.int'
12981298

1299+
[case testDeferredClassContext]
1300+
class A:
1301+
def f(self) -> str: return 'foo'
1302+
class B(A):
1303+
def f(self) -> str: return self.x
1304+
def initialize(self): self.x = 'bar'
1305+
[out]
1306+
12991307

13001308
-- Scripts and __main__
13011309

0 commit comments

Comments
 (0)