Skip to content

Commit 2f3d4a2

Browse files
rowilliagvanrossum
authored andcommitted
Allow instances of a class to access inner class definitions on that class. (#3636)
This fixes #3635
1 parent 3427a5f commit 2f3d4a2

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

mypy/checkmember.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,13 @@ def analyze_member_var_access(name: str, itype: Instance, info: TypeInfo,
227227
# The associated Var node of a decorator contains the type.
228228
v = vv.var
229229

230+
if isinstance(vv, TypeInfo):
231+
# If the associated variable is a TypeInfo synthesize a Var node for
232+
# the purposes of type checking. This enables us to type check things
233+
# like accessing class attributes on an inner class.
234+
v = Var(name, type=type_object_type(vv, builtin_type))
235+
v.info = info
236+
230237
if isinstance(v, Var):
231238
return analyze_var(name, v, itype, info, node, is_lvalue, msg,
232239
original_type, not_ready_callback, chk=chk)

test-data/unit/check-classes.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,21 @@ def produce() -> Bar:
681681
reveal_type(Bar().make_int) # E: Revealed type is 'def () -> builtins.int'
682682
return Bar()
683683

684+
[case testInnerClassPropertyAccess]
685+
class Foo:
686+
class Meta:
687+
name = 'Bar'
688+
meta = Meta
689+
690+
reveal_type(Foo.Meta) # E: Revealed type is 'def () -> __main__.Foo.Meta'
691+
reveal_type(Foo.meta) # E: Revealed type is 'def () -> __main__.Foo.Meta'
692+
reveal_type(Foo.Meta.name) # E: Revealed type is 'builtins.str'
693+
reveal_type(Foo.meta.name) # E: Revealed type is 'builtins.str'
694+
reveal_type(Foo().Meta) # E: Revealed type is 'def () -> __main__.Foo.Meta'
695+
reveal_type(Foo().meta) # E: Revealed type is 'def () -> __main__.Foo.Meta'
696+
reveal_type(Foo().meta.name) # E: Revealed type is 'builtins.str'
697+
reveal_type(Foo().Meta.name) # E: Revealed type is 'builtins.str'
698+
684699
-- Declaring attribute type in method
685700
-- ----------------------------------
686701

0 commit comments

Comments
 (0)