-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Implement ClassVar semantics (fixes #2771) #2873
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
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
d6b370d
Implement ClassVar semantics (fixes #2771)
miedzinski 950b383
Fix type annotations
miedzinski cdfdbbc
Remove ClassVarType, use Var.is_classvar flag
miedzinski 01a7a69
Add test case against TypeVar
miedzinski d52b4e3
Fix if statement in check_classvar_definition
miedzinski 15e1e85
Change error message about ClassVar arg count
miedzinski 781245f
Add more tests
miedzinski cd61a5d
Remove duplicate test case
miedzinski 9c29911
Move ClassVar override checks to TypeChecker
miedzinski b618718
Prohibit ClassVar inside other types or in signatures
miedzinski cb6786f
Prohibit defining ClassVars on self
miedzinski a427d61
Add more tests
miedzinski 35e2c68
Fix analysing implicit tuple types
miedzinski e121158
Add more meaningful error message on attribute override
miedzinski 5e2aafc
Add better error message on assignments
miedzinski 137215e
Add more precise errors on ClassVar definitions
miedzinski 5dd131a
Minor style improvements
miedzinski 30a4185
Prohibit ClassVars in for and with statements
miedzinski bcce34d
Rename check_classvar_definition to is_classvar
miedzinski 7ddca4b
Don't consider types in signatures as nested
miedzinski 92b3532
Prohibit generic class variables
miedzinski 20b1abe
Prohibit access to generic instance variables via class
miedzinski 3362e65
Merge branch 'master' into classvar
miedzinski 5430b32
Add incremental checking test
miedzinski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,13 @@ | ||
"""Semantic analysis of types""" | ||
|
||
from collections import OrderedDict | ||
from typing import Callable, cast, List, Optional | ||
from typing import Callable, List, Optional, Set | ||
|
||
from mypy.types import ( | ||
Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance, | ||
Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance, TypeVarId, | ||
AnyType, CallableType, Void, NoneTyp, DeletedType, TypeList, TypeVarDef, TypeVisitor, | ||
StarType, PartialType, EllipsisType, UninhabitedType, TypeType, get_typ_args, set_typ_args, | ||
get_type_vars, | ||
) | ||
from mypy.nodes import ( | ||
BOUND_TVAR, UNBOUND_TVAR, TYPE_ALIAS, UNBOUND_IMPORTED, | ||
|
@@ -81,11 +82,15 @@ def __init__(self, | |
lookup_func: Callable[[str, Context], SymbolTableNode], | ||
lookup_fqn_func: Callable[[str], SymbolTableNode], | ||
fail_func: Callable[[str, Context], None], *, | ||
aliasing: bool = False) -> None: | ||
aliasing: bool = False, | ||
allow_tuple_literal: bool = False) -> None: | ||
self.lookup = lookup_func | ||
self.lookup_fqn_func = lookup_fqn_func | ||
self.fail = fail_func | ||
self.aliasing = aliasing | ||
self.allow_tuple_literal = allow_tuple_literal | ||
# Positive if we are analyzing arguments of another (outer) type | ||
self.nesting_level = 0 | ||
|
||
def visit_unbound_type(self, t: UnboundType) -> Type: | ||
if t.optional: | ||
|
@@ -120,7 +125,7 @@ def visit_unbound_type(self, t: UnboundType) -> Type: | |
return self.builtin_type('builtins.tuple') | ||
if len(t.args) == 2 and isinstance(t.args[1], EllipsisType): | ||
# Tuple[T, ...] (uniform, variable-length tuple) | ||
instance = self.builtin_type('builtins.tuple', [t.args[0].accept(self)]) | ||
instance = self.builtin_type('builtins.tuple', [self.anal_type(t.args[0])]) | ||
instance.line = t.line | ||
return instance | ||
return self.tuple_type(self.anal_array(t.args)) | ||
|
@@ -132,22 +137,34 @@ def visit_unbound_type(self, t: UnboundType) -> Type: | |
if len(t.args) != 1: | ||
self.fail('Optional[...] must have exactly one type argument', t) | ||
return AnyType() | ||
items = self.anal_array(t.args) | ||
item = self.anal_type(t.args[0]) | ||
if experiments.STRICT_OPTIONAL: | ||
return UnionType.make_simplified_union([items[0], NoneTyp()]) | ||
return UnionType.make_simplified_union([item, NoneTyp()]) | ||
else: | ||
# Without strict Optional checking Optional[t] is just an alias for t. | ||
return items[0] | ||
return item | ||
elif fullname == 'typing.Callable': | ||
return self.analyze_callable_type(t) | ||
elif fullname == 'typing.Type': | ||
if len(t.args) == 0: | ||
return TypeType(AnyType(), line=t.line) | ||
if len(t.args) != 1: | ||
self.fail('Type[...] must have exactly one type argument', t) | ||
items = self.anal_array(t.args) | ||
item = items[0] | ||
item = self.anal_type(t.args[0]) | ||
return TypeType(item, line=t.line) | ||
elif fullname == 'typing.ClassVar': | ||
if self.nesting_level > 0: | ||
self.fail('Invalid type: ClassVar nested inside other type', t) | ||
if len(t.args) == 0: | ||
return AnyType(line=t.line) | ||
if len(t.args) != 1: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think a bare |
||
self.fail('ClassVar[...] must have at most one type argument', t) | ||
return AnyType() | ||
item = self.anal_type(t.args[0]) | ||
if isinstance(item, TypeVarType) or get_type_vars(item): | ||
self.fail('Invalid type: ClassVar cannot be generic', t) | ||
return AnyType() | ||
return item | ||
elif fullname == 'mypy_extensions.NoReturn': | ||
return UninhabitedType(is_noreturn=True) | ||
elif sym.kind == TYPE_ALIAS: | ||
|
@@ -290,31 +307,38 @@ def visit_type_var(self, t: TypeVarType) -> Type: | |
return t | ||
|
||
def visit_callable_type(self, t: CallableType) -> Type: | ||
return t.copy_modified(arg_types=self.anal_array(t.arg_types), | ||
ret_type=t.ret_type.accept(self), | ||
return t.copy_modified(arg_types=self.anal_array(t.arg_types, nested=False), | ||
ret_type=self.anal_type(t.ret_type, nested=False), | ||
fallback=t.fallback or self.builtin_type('builtins.function'), | ||
variables=self.anal_var_defs(t.variables)) | ||
|
||
def visit_tuple_type(self, t: TupleType) -> Type: | ||
if t.implicit: | ||
# Types such as (t1, t2, ...) only allowed in assignment statements. They'll | ||
# generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead. | ||
if t.implicit and not self.allow_tuple_literal: | ||
self.fail('Invalid tuple literal type', t) | ||
return AnyType() | ||
star_count = sum(1 for item in t.items if isinstance(item, StarType)) | ||
if star_count > 1: | ||
self.fail('At most one star type allowed in a tuple', t) | ||
return AnyType() | ||
if t.implicit: | ||
return TupleType([AnyType() for _ in t.items], | ||
self.builtin_type('builtins.tuple'), | ||
t.line) | ||
else: | ||
return AnyType() | ||
fallback = t.fallback if t.fallback else self.builtin_type('builtins.tuple', [AnyType()]) | ||
return TupleType(self.anal_array(t.items), fallback, t.line) | ||
|
||
def visit_typeddict_type(self, t: TypedDictType) -> Type: | ||
items = OrderedDict([ | ||
(item_name, item_type.accept(self)) | ||
(item_name, self.anal_type(item_type)) | ||
for (item_name, item_type) in t.items.items() | ||
]) | ||
return TypedDictType(items, t.fallback) | ||
|
||
def visit_star_type(self, t: StarType) -> Type: | ||
return StarType(t.type.accept(self), t.line) | ||
return StarType(self.anal_type(t.type), t.line) | ||
|
||
def visit_union_type(self, t: UnionType) -> Type: | ||
return UnionType(self.anal_array(t.items), t.line) | ||
|
@@ -327,7 +351,7 @@ def visit_ellipsis_type(self, t: EllipsisType) -> Type: | |
return AnyType() | ||
|
||
def visit_type_type(self, t: TypeType) -> Type: | ||
return TypeType(t.item.accept(self), line=t.line) | ||
return TypeType(self.anal_type(t.item), line=t.line) | ||
|
||
def analyze_callable_type(self, t: UnboundType) -> Type: | ||
fallback = self.builtin_type('builtins.function') | ||
|
@@ -340,7 +364,7 @@ def analyze_callable_type(self, t: UnboundType) -> Type: | |
fallback=fallback, | ||
is_ellipsis_args=True) | ||
elif len(t.args) == 2: | ||
ret_type = t.args[1].accept(self) | ||
ret_type = self.anal_type(t.args[1]) | ||
if isinstance(t.args[0], TypeList): | ||
# Callable[[ARG, ...], RET] (ordinary callable type) | ||
args = t.args[0].items | ||
|
@@ -364,12 +388,21 @@ def analyze_callable_type(self, t: UnboundType) -> Type: | |
self.fail('Invalid function type', t) | ||
return AnyType() | ||
|
||
def anal_array(self, a: List[Type]) -> List[Type]: | ||
def anal_array(self, a: List[Type], nested: bool = True) -> List[Type]: | ||
res = [] # type: List[Type] | ||
for t in a: | ||
res.append(t.accept(self)) | ||
res.append(self.anal_type(t, nested)) | ||
return res | ||
|
||
def anal_type(self, t: Type, nested: bool = True) -> Type: | ||
if nested: | ||
self.nesting_level += 1 | ||
try: | ||
return t.accept(self) | ||
finally: | ||
if nested: | ||
self.nesting_level -= 1 | ||
|
||
def anal_var_defs(self, var_defs: List[TypeVarDef]) -> List[TypeVarDef]: | ||
a = [] # type: List[TypeVarDef] | ||
for vd in var_defs: | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this change really necessary? I am asking for two reasons:
TupleType
with corresponding number ofAny
s as items, instead of just plainAnyType()
intypeanal.py
code)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My bad. I've restored old behaviour, although in
TypeAnalyser
. This is needed if we want to fail onSince I've removed the test for this we could allow this, but these variables wouldn't get
is_classvar
flag. I would keep it as is.