Skip to content

Commit d6b370d

Browse files
committed
Implement ClassVar semantics (fixes python#2771)
1 parent 95fd5fb commit d6b370d

11 files changed

Lines changed: 141 additions & 5 deletions

File tree

‎mypy/checker.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from mypy import nodes
2626
from mypy.types import (
2727
Type, AnyType, CallableType, Void, FunctionLike, Overloaded, TupleType, TypedDictType,
28-
Instance, NoneTyp, ErrorType, strip_type, TypeType,
28+
Instance, NoneTyp, ErrorType, strip_type, TypeType, ClassVarType,
2929
UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarDef,
3030
true_only, false_only, function_type, is_named_instance
3131
)
@@ -1575,6 +1575,9 @@ def check_member_assignment(self, instance_type: Type, attribute_type: Type,
15751575
15761576
Return the inferred rvalue_type and whether to infer anything about the attribute type
15771577
"""
1578+
if isinstance(instance_type, Instance) and isinstance(attribute_type, ClassVarType):
1579+
self.msg.fail("Illegal assignment to class variable", context)
1580+
15781581
# Descriptors don't participate in class-attribute access
15791582
if ((isinstance(instance_type, FunctionLike) and instance_type.is_type_obj()) or
15801583
isinstance(instance_type, TypeType)):

‎mypy/checkexpr.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from mypy.types import (
88
Type, AnyType, CallableType, Overloaded, NoneTyp, Void, TypeVarDef,
99
TupleType, TypedDictType, Instance, TypeVarType, ErasedType, UnionType,
10-
PartialType, DeletedType, UnboundType, UninhabitedType, TypeType,
10+
PartialType, DeletedType, UnboundType, UninhabitedType, TypeType, ClassVarType,
1111
true_only, false_only, is_named_instance, function_type, callable_type, FunctionLike,
1212
get_typ_args, set_typ_args,
1313
StarType)
@@ -2218,6 +2218,8 @@ def bool_type(self) -> Instance:
22182218
return self.named_type('builtins.bool')
22192219

22202220
def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type:
2221+
if isinstance(known_type, ClassVarType):
2222+
known_type = known_type.item
22212223
if expr.literal >= LITERAL_TYPE:
22222224
restriction = self.chk.binder.get(expr)
22232225
if restriction:

‎mypy/semanal.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
from mypy.errors import Errors, report_internal_error
7474
from mypy.types import (
7575
NoneTyp, CallableType, Overloaded, Instance, Type, TypeVarType, AnyType,
76-
FunctionLike, UnboundType, TypeList, TypeVarDef, TypeType,
76+
FunctionLike, UnboundType, TypeList, TypeVarDef, TypeType, ClassVarType,
7777
TupleType, UnionType, StarType, EllipsisType, function_type, TypedDictType,
7878
)
7979
from mypy.nodes import implicit_module_attrs
@@ -1363,6 +1363,7 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
13631363
self.process_typevar_declaration(s)
13641364
self.process_namedtuple_definition(s)
13651365
self.process_typeddict_definition(s)
1366+
self.check_classvar_definition(s)
13661367

13671368
if (len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) and
13681369
s.lvalues[0].name == '__all__' and s.lvalues[0].kind == GDEF and
@@ -2159,6 +2160,10 @@ def build_typeddict_typeinfo(self, name: str, items: List[str],
21592160

21602161
return info
21612162

2163+
def check_classvar_definition(self, s: AssignmentStmt):
2164+
if isinstance(s.type, ClassVarType) and not self.is_class_scope():
2165+
self.fail("Invalid ClassVar definition", s)
2166+
21622167
def visit_decorator(self, dec: Decorator) -> None:
21632168
for d in dec.decorators:
21642169
d.accept(self)

‎mypy/subtypes.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
from mypy.types import (
44
Type, AnyType, UnboundType, TypeVisitor, ErrorType, FormalArgument, Void, NoneTyp,
55
Instance, TypeVarType, CallableType, TupleType, TypedDictType, UnionType, Overloaded,
6-
ErasedType, TypeList, PartialType, DeletedType, UninhabitedType, TypeType, is_named_instance
6+
ErasedType, TypeList, PartialType, DeletedType, UninhabitedType, TypeType, is_named_instance,
7+
ClassVarType,
78
)
89
import mypy.applytype
910
import mypy.constraints
@@ -52,6 +53,9 @@ def is_subtype(left: Type, right: Type,
5253
return any(is_subtype(left, item, type_parameter_checker,
5354
ignore_pos_arg_names=ignore_pos_arg_names)
5455
for item in right.items)
56+
elif isinstance(right, ClassVarType):
57+
return is_subtype(left, right.item, type_parameter_checker,
58+
ignore_pos_arg_names=ignore_pos_arg_names)
5559
else:
5660
return left.accept(SubtypeVisitor(right, type_parameter_checker,
5761
ignore_pos_arg_names=ignore_pos_arg_names))

‎mypy/test/testcheck.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
'check-varargs.test',
7575
'check-newsyntax.test',
7676
'check-underscores.test',
77+
'check-classvar.test',
7778
]
7879

7980
files.extend(fast_parser_files)

‎mypy/test/testsemanal.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
'semanal-abstractclasses.test',
3131
'semanal-namedtuple.test',
3232
'semanal-typeddict.test',
33+
'semanal-classvar.test',
3334
'semanal-python2.test']
3435

3536

‎mypy/typeanal.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from typing import Callable, cast, List, Optional
55

66
from mypy.types import (
7-
Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance,
7+
Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance, ClassVarType,
88
AnyType, CallableType, Void, NoneTyp, DeletedType, TypeList, TypeVarDef, TypeVisitor,
99
StarType, PartialType, EllipsisType, UninhabitedType, TypeType, get_typ_args, set_typ_args,
1010
)
@@ -148,6 +148,12 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
148148
items = self.anal_array(t.args)
149149
item = items[0]
150150
return TypeType(item, line=t.line)
151+
elif fullname == 'typing.ClassVar':
152+
if len(t.args) != 1:
153+
self.fail('ClassVar[...] must have exactly one type argument', t)
154+
return AnyType()
155+
items = self.anal_array(t.args)
156+
return ClassVarType(items[0])
151157
elif fullname == 'mypy_extensions.NoReturn':
152158
return UninhabitedType(is_noreturn=True)
153159
elif sym.kind == TYPE_ALIAS:

‎mypy/types.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,6 +1189,29 @@ def deserialize(cls, data: JsonDict) -> 'TypeType':
11891189
return TypeType(Type.deserialize(data['item']))
11901190

11911191

1192+
class ClassVarType(Type):
1193+
"""The ClassVar[T] type.
1194+
1195+
In all typechecking scenarios, behaves like T.
1196+
"""
1197+
item = None # type: Type
1198+
1199+
def __init__(self, item: Type, *, line: int = -1, column: int = -1) -> None:
1200+
super().__init__(line, column)
1201+
self.item = item
1202+
1203+
def accept(self, visitor: 'TypeVisitor[T]') -> T:
1204+
return visitor.visit_classvar_type(self)
1205+
1206+
def serialize(self) -> JsonDict:
1207+
return {'.class': 'ClassVarType', 'item': self.item.serialize()}
1208+
1209+
@classmethod
1210+
def deserialize(cls, data: JsonDict) -> 'TypeType':
1211+
assert data['.class'] == 'ClassVarType'
1212+
return ClassVarType(Type.deserialize(data['item']))
1213+
1214+
11921215
#
11931216
# Visitor-related classes
11941217
#
@@ -1280,6 +1303,9 @@ def visit_ellipsis_type(self, t: EllipsisType) -> T:
12801303
def visit_type_type(self, t: TypeType) -> T:
12811304
pass
12821305

1306+
def visit_classvar_type(self, t: ClassVarType) -> T:
1307+
pass
1308+
12831309

12841310
class TypeTranslator(TypeVisitor[Type]):
12851311
"""Identity type transformation.
@@ -1513,6 +1539,9 @@ def visit_ellipsis_type(self, t: EllipsisType) -> str:
15131539
def visit_type_type(self, t: TypeType) -> str:
15141540
return 'Type[{}]'.format(t.item.accept(self))
15151541

1542+
def visit_classvar_type(self, t: TypeType) -> str:
1543+
return 'ClassVar[{}]'.format(t.item.accept(self))
1544+
15161545
def list_str(self, a: List[Type]) -> str:
15171546
"""Convert items of an array to strings (pretty-print types)
15181547
and join the results with commas.

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
[case testAssignmentOnClass]
2+
from typing import ClassVar
3+
class A:
4+
x = 1 # type: ClassVar[int]
5+
A.x = 2
6+
7+
[case testAssignmentOnInstance]
8+
from typing import ClassVar
9+
class A:
10+
x = 1 # type: ClassVar[int]
11+
A().x = 2
12+
[out]
13+
main:4: error: Illegal assignment to class variable
14+
15+
[case testAssignmentOnSubclass]
16+
from typing import ClassVar
17+
class A:
18+
x = 1 # type: ClassVar[int]
19+
class B(A):
20+
pass
21+
B().x = 2
22+
[out]
23+
main:6: error: Illegal assignment to class variable
24+
25+
[case testReadingFromInstance]
26+
from typing import ClassVar
27+
class A:
28+
x = 1 # type: ClassVar[int]
29+
A().x
30+
31+
[case testTypecheck]
32+
from typing import ClassVar
33+
class A:
34+
x = 1 # type: ClassVar[int]
35+
y = A.x # type: int
36+
37+
[case testInfer]
38+
from typing import ClassVar
39+
class A:
40+
x = 1 # type: ClassVar[int]
41+
y = A.x
42+
reveal_type(y)
43+
[out]
44+
main:5: error: Revealed type is 'builtins.int'

‎test-data/unit/lib-stub/typing.pyi‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ _promote = 0
1717
NamedTuple = 0
1818
Type = 0
1919
no_type_check = 0
20+
ClassVar = 0
2021

2122
# Type aliases.
2223
List = 0

0 commit comments

Comments
 (0)