From 51db723843e21733ec7cd4758d87ee3b8d28a3f4 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Mon, 18 Jan 2021 18:50:41 -0800 Subject: [PATCH 01/11] merge typevartype into typevardef --- mypy/types.py | 80 +++++++++------------------------------------------ 1 file changed, 14 insertions(+), 66 deletions(-) diff --git a/mypy/types.py b/mypy/types.py index bf138f343b5a..9424474a1066 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -338,7 +338,7 @@ def is_meta_var(self) -> bool: return self.meta_level > 0 -class TypeVarLikeDef(mypy.nodes.Context): +class TypeVarLikeDef(ProperType): name = '' # Name (may be qualified) fullname = '' # Fully qualified name id = None # type: TypeVarId @@ -353,9 +353,6 @@ def __init__( id = TypeVarId(id) self.id = id - def __repr__(self) -> str: - return self.name - def serialize(self) -> JsonDict: raise NotImplementedError @@ -385,13 +382,16 @@ def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef': return TypeVarDef(old.name, old.fullname, new_id, old.values, old.upper_bound, old.variance, old.line, old.column) - def __repr__(self) -> str: - if self.values: - return '{} in {}'.format(self.name, tuple(self.values)) - elif not is_named_instance(self.upper_bound, 'builtins.object'): - return '{} <: {}'.format(self.name, self.upper_bound) - else: - return self.name + def accept(self, visitor: 'TypeVisitor[T]') -> T: + return visitor.visit_type_var(self) + + def __hash__(self) -> int: + return hash(self.id) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeVarType): + return NotImplemented + return self.id == other.id def serialize(self) -> JsonDict: assert not self.id.is_meta_var() @@ -419,6 +419,9 @@ def deserialize(cls, data: JsonDict) -> 'TypeVarDef': class ParamSpecDef(TypeVarLikeDef): """Definition of a single ParamSpec variable.""" + def __repr__(self) -> str: + return self.name + def serialize(self) -> JsonDict: assert not self.id.is_meta_var() return { @@ -900,61 +903,6 @@ def has_readable_member(self, name: str) -> bool: return self.type.has_readable_member(name) -class TypeVarType(ProperType): - """A type variable type. - - This refers to either a class type variable (id > 0) or a function - type variable (id < 0). - """ - - __slots__ = ('name', 'fullname', 'id', 'values', 'upper_bound', 'variance') - - def __init__(self, binder: TypeVarDef, line: int = -1, column: int = -1) -> None: - super().__init__(line, column) - self.name = binder.name # Name of the type variable (for messages and debugging) - self.fullname = binder.fullname # type: str - self.id = binder.id # type: TypeVarId - # Value restriction, empty list if no restriction - self.values = binder.values # type: List[Type] - # Upper bound for values - self.upper_bound = binder.upper_bound # type: Type - # See comments in TypeVarDef for more about variance. - self.variance = binder.variance # type: int - - def accept(self, visitor: 'TypeVisitor[T]') -> T: - return visitor.visit_type_var(self) - - def __hash__(self) -> int: - return hash(self.id) - - def __eq__(self, other: object) -> bool: - if not isinstance(other, TypeVarType): - return NotImplemented - return self.id == other.id - - def serialize(self) -> JsonDict: - assert not self.id.is_meta_var() - return {'.class': 'TypeVarType', - 'name': self.name, - 'fullname': self.fullname, - 'id': self.id.raw_id, - 'values': [v.serialize() for v in self.values], - 'upper_bound': self.upper_bound.serialize(), - 'variance': self.variance, - } - - @classmethod - def deserialize(cls, data: JsonDict) -> 'TypeVarType': - assert data['.class'] == 'TypeVarType' - tvdef = TypeVarDef(data['name'], - data['fullname'], - data['id'], - [deserialize_type(v) for v in data['values']], - deserialize_type(data['upper_bound']), - data['variance']) - return TypeVarType(tvdef) - - class FunctionLike(ProperType): """Abstract base class for function types.""" From 4e667df23743a4df9ab0b9bd2180ec725bbd153b Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Mon, 18 Jan 2021 19:16:28 -0800 Subject: [PATCH 02/11] turn typevardef into typevartype --- mypy/applytype.py | 4 +-- mypy/checker.py | 6 ++-- mypy/checkexpr.py | 55 +++++++++++++++++-------------------- mypy/expandtype.py | 8 +++--- mypy/fixup.py | 4 +-- mypy/messages.py | 4 +-- mypy/nodes.py | 6 ++-- mypy/plugins/attrs.py | 11 ++++---- mypy/plugins/common.py | 6 ++-- mypy/plugins/dataclasses.py | 9 +++--- mypy/plugins/default.py | 10 +++---- mypy/semanal.py | 8 +++--- mypy/semanal_namedtuple.py | 6 ++-- mypy/server/astdiff.py | 2 +- mypy/server/astmerge.py | 6 ++-- mypy/test/testtypes.py | 16 +++++------ mypy/test/typefixture.py | 8 +++--- mypy/tvar_scope.py | 4 +-- mypy/typeanal.py | 8 +++--- mypy/typeops.py | 4 +-- mypy/types.py | 20 +++++++------- mypy/typevars.py | 2 +- 22 files changed, 100 insertions(+), 107 deletions(-) diff --git a/mypy/applytype.py b/mypy/applytype.py index 2bc2fa92f7dc..6c0a1521909d 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -5,7 +5,7 @@ from mypy.expandtype import expand_type from mypy.types import ( Type, TypeVarId, TypeVarType, CallableType, AnyType, PartialType, get_proper_types, - TypeVarDef, TypeVarLikeDef, ProperType + TypeVarType, TypeVarLikeDef, ProperType ) from mypy.nodes import Context @@ -19,7 +19,7 @@ def get_target_type( skip_unsatisfied: bool ) -> Optional[Type]: # TODO(shantanu): fix for ParamSpecDef - assert isinstance(tvar, TypeVarDef) + assert isinstance(tvar, TypeVarType) values = get_proper_types(tvar.values) if values: if isinstance(type, AnyType): diff --git a/mypy/checker.py b/mypy/checker.py index fce7e7d7a08e..1ef80faee88f 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -32,7 +32,7 @@ from mypy.types import ( Type, AnyType, CallableType, FunctionLike, Overloaded, TupleType, TypedDictType, Instance, NoneType, strip_type, TypeType, TypeOfAny, - UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarDef, + UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarType, is_named_instance, union_items, TypeQuery, LiteralType, is_optional, remove_optional, TypeTranslator, StarType, get_proper_type, ProperType, get_proper_types, is_literal_type, TypeAliasType, TypeGuardType) @@ -1395,7 +1395,7 @@ def expand_typevars(self, defn: FuncItem, tvars += defn.info.defn.type_vars or [] # TODO(shantanu): audit for paramspec for tvar in tvars: - if isinstance(tvar, TypeVarDef) and tvar.values: + if isinstance(tvar, TypeVarType) and tvar.values: subst.append([(tvar.id, value) for value in tvar.values]) # Make a copy of the function to check for each combination of # value restricted type variables. (Except when running mypyc, @@ -5352,7 +5352,7 @@ def detach_callable(typ: CallableType) -> CallableType: for var in set(all_type_vars): if var.fullname not in used_type_var_names: continue - new_variables.append(TypeVarDef( + new_variables.append(TypeVarType( name=var.name, fullname=var.fullname, id=var.id, diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index cbfa5dbc0b4e..f85c2e211e44 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -14,7 +14,7 @@ make_optional_type, ) from mypy.types import ( - Type, AnyType, CallableType, Overloaded, NoneType, TypeGuardType, TypeVarDef, + Type, AnyType, CallableType, Overloaded, NoneType, TypeVarType, TypeGuardType, TupleType, TypedDictType, Instance, TypeVarType, ErasedType, UnionType, PartialType, DeletedType, UninhabitedType, TypeType, TypeOfAny, LiteralType, LiteralValue, is_named_instance, FunctionLike, @@ -1890,8 +1890,8 @@ def combine_function_signatures(self, types: Sequence[Type]) -> Union[AnyType, C # same thing. # # This function will make sure that all instances of that TypeVar 'T' - # refer to the same underlying TypeVarType and TypeVarDef objects to - # simplify the union-ing logic below. + # refer to the same underlying TypeVarType objects to simplify the union-ing + # logic below. # # (If the user did *not* mean for 'T' to be consistently bound to the # same type in their overloads, well, their code is probably too @@ -3264,13 +3264,12 @@ def check_lst_expr(self, items: List[Expression], fullname: str, # Used for list and set expressions, as well as for tuples # containing star expressions that don't refer to a # Tuple. (Note: "lst" stands for list-set-tuple. :-) - tvdef = TypeVarDef('T', 'T', -1, [], self.object_type()) - tv = TypeVarType(tvdef) + tvdef = TypeVarType('T', 'T', -1, [], self.object_type()) constructor = CallableType( - [tv], + [tvdef], [nodes.ARG_STAR], [None], - self.chk.named_generic_type(fullname, [tv]), + self.chk.named_generic_type(fullname, [tvdef]), self.named_type('builtins.function'), name=tag, variables=[tvdef]) @@ -3422,10 +3421,8 @@ def visit_dict_expr(self, e: DictExpr) -> Type: tup.column = value.column args.append(tup) # Define type variables (used in constructors below). - ktdef = TypeVarDef('KT', 'KT', -1, [], self.object_type()) - vtdef = TypeVarDef('VT', 'VT', -2, [], self.object_type()) - kt = TypeVarType(ktdef) - vt = TypeVarType(vtdef) + ktdef = TypeVarType('KT', 'KT', -1, [], self.object_type()) + vtdef = TypeVarType('VT', 'VT', -2, [], self.object_type()) rv = None # Call dict(*args), unless it's empty and stargs is not. if args or not stargs: @@ -3433,10 +3430,10 @@ def visit_dict_expr(self, e: DictExpr) -> Type: # # def (*v: Tuple[kt, vt]) -> Dict[kt, vt]: ... constructor = CallableType( - [TupleType([kt, vt], self.named_type('builtins.tuple'))], + [TupleType([ktdef, vtdef], self.named_type('builtins.tuple'))], [nodes.ARG_STAR], [None], - self.chk.named_generic_type('builtins.dict', [kt, vt]), + self.chk.named_generic_type('builtins.dict', [ktdef, vtdef]), self.named_type('builtins.function'), name='', variables=[ktdef, vtdef]) @@ -3450,10 +3447,10 @@ def visit_dict_expr(self, e: DictExpr) -> Type: for arg in stargs: if rv is None: constructor = CallableType( - [self.chk.named_generic_type('typing.Mapping', [kt, vt])], + [self.chk.named_generic_type('typing.Mapping', [ktdef, vtdef])], [nodes.ARG_POS], [None], - self.chk.named_generic_type('builtins.dict', [kt, vt]), + self.chk.named_generic_type('builtins.dict', [ktdef, vtdef]), self.named_type('builtins.function'), name='', variables=[ktdef, vtdef]) @@ -3746,8 +3743,8 @@ def check_generator_or_comprehension(self, gen: GeneratorExpr, # Infer the type of the list comprehension by using a synthetic generic # callable type. - tvdef = TypeVarDef('T', 'T', -1, [], self.object_type()) - tv_list = [TypeVarType(tvdef)] # type: List[Type] + tvdef = TypeVarType('T', 'T', -1, [], self.object_type()) + tv_list = [tvdef] # type: List[Type] constructor = CallableType( tv_list, [nodes.ARG_POS], @@ -3766,15 +3763,13 @@ def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type: # Infer the type of the list comprehension by using a synthetic generic # callable type. - ktdef = TypeVarDef('KT', 'KT', -1, [], self.object_type()) - vtdef = TypeVarDef('VT', 'VT', -2, [], self.object_type()) - kt = TypeVarType(ktdef) - vt = TypeVarType(vtdef) + ktdef = TypeVarType('KT', 'KT', -1, [], self.object_type()) + vtdef = TypeVarType('VT', 'VT', -2, [], self.object_type()) constructor = CallableType( - [kt, vt], + [ktdef, vtdef], [nodes.ARG_POS, nodes.ARG_POS], [None, None], - self.chk.named_generic_type('builtins.dict', [kt, vt]), + self.chk.named_generic_type('builtins.dict', [ktdef, vtdef]), self.chk.named_type('builtins.function'), name='', variables=[ktdef, vtdef]) @@ -4424,7 +4419,7 @@ def all_same_types(types: List[Type]) -> bool: def merge_typevars_in_callables_by_name( - callables: Sequence[CallableType]) -> Tuple[List[CallableType], List[TypeVarDef]]: + callables: Sequence[CallableType]) -> Tuple[List[CallableType], List[TypeVarType]]: """Takes all the typevars present in the callables and 'combines' the ones with the same name. For example, suppose we have two callables with signatures "f(x: T, y: S) -> T" and @@ -4433,18 +4428,18 @@ def merge_typevars_in_callables_by_name( distinct ids.) If we pass in both callables into this function, it returns a a list containing two - new callables that are identical in signature, but use the same underlying TypeVarDef - and TypeVarType objects for T and S. + new callables that are identical in signature, but use the same underlying TypeVarType + for T and S. This is useful if we want to take the output lists and "merge" them into one callable in some way -- for example, when unioning together overloads. - Returns both the new list of callables and a list of all distinct TypeVarDef objects used. + Returns both the new list of callables and a list of all distinct TypeVarType objects used. """ output = [] # type: List[CallableType] unique_typevars = {} # type: Dict[str, TypeVarType] - variables = [] # type: List[TypeVarDef] + variables = [] # type: List[TypeVarType] for target in callables: if target.is_generic(): @@ -4455,8 +4450,8 @@ def merge_typevars_in_callables_by_name( name = tvdef.fullname if name not in unique_typevars: # TODO(shantanu): fix for ParamSpecDef - assert isinstance(tvdef, TypeVarDef) - unique_typevars[name] = TypeVarType(tvdef) + assert isinstance(tvdef, TypeVarType) + unique_typevars[name] = tvdef variables.append(tvdef) rename[tvdef.id] = unique_typevars[name] diff --git a/mypy/expandtype.py b/mypy/expandtype.py index f98e0750743b..1c512d707299 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -4,7 +4,7 @@ Type, Instance, CallableType, TypeVisitor, UnboundType, AnyType, NoneType, TypeVarType, Overloaded, TupleType, TypedDictType, UnionType, ErasedType, PartialType, DeletedType, UninhabitedType, TypeType, TypeVarId, - FunctionLike, TypeVarDef, LiteralType, get_proper_type, ProperType, + FunctionLike, TypeVarType, LiteralType, get_proper_type, ProperType, TypeAliasType) @@ -41,10 +41,10 @@ def freshen_function_type_vars(callee: F) -> F: tvmap = {} # type: Dict[TypeVarId, Type] for v in callee.variables: # TODO(shantanu): fix for ParamSpecDef - assert isinstance(v, TypeVarDef) - tvdef = TypeVarDef.new_unification_variable(v) + assert isinstance(v, TypeVarType) + tvdef = TypeVarType.new_unification_variable(v) tvdefs.append(tvdef) - tvmap[v.id] = TypeVarType(tvdef) + tvmap[v.id] = tvdef fresh = cast(CallableType, expand_type(callee, tvmap)).copy_modified(variables=tvdefs) return cast(F, fresh) else: diff --git a/mypy/fixup.py b/mypy/fixup.py index b90dba971e4f..11bb1b6f2624 100644 --- a/mypy/fixup.py +++ b/mypy/fixup.py @@ -11,7 +11,7 @@ from mypy.types import ( CallableType, Instance, Overloaded, TupleType, TypedDictType, TypeVarType, UnboundType, UnionType, TypeVisitor, LiteralType, - TypeType, NOT_READY, TypeAliasType, AnyType, TypeOfAny, TypeVarDef + TypeType, NOT_READY, TypeAliasType, AnyType, TypeOfAny, TypeVarType ) from mypy.visitor import NodeVisitor from mypy.lookup import lookup_fully_qualified @@ -184,7 +184,7 @@ def visit_callable_type(self, ct: CallableType) -> None: if ct.ret_type is not None: ct.ret_type.accept(self) for v in ct.variables: - if isinstance(v, TypeVarDef): + if isinstance(v, TypeVarType): if v.values: for val in v.values: val.accept(self) diff --git a/mypy/messages.py b/mypy/messages.py index cd0b491768a9..63c77efcd7dc 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -21,7 +21,7 @@ from mypy.errors import Errors from mypy.types import ( Type, CallableType, Instance, TypeVarType, TupleType, TypedDictType, LiteralType, - UnionType, NoneType, AnyType, Overloaded, FunctionLike, DeletedType, TypeType, TypeVarDef, + UnionType, NoneType, AnyType, Overloaded, FunctionLike, DeletedType, TypeType, TypeVarType, UninhabitedType, TypeOfAny, UnboundType, PartialType, get_proper_type, ProperType, get_proper_types ) @@ -1873,7 +1873,7 @@ def [T <: int] f(self, x: int, y: T) -> None if tp.variables: tvars = [] for tvar in tp.variables: - if isinstance(tvar, TypeVarDef): + if isinstance(tvar, TypeVarType): upper_bound = get_proper_type(tvar.upper_bound) if (isinstance(upper_bound, Instance) and upper_bound.type.fullname != 'builtins.object'): diff --git a/mypy/nodes.py b/mypy/nodes.py index 76521e8c2b38..3cf36048b6cd 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -916,7 +916,7 @@ class ClassDef(Statement): name = None # type: str # Name of the class without module prefix fullname = None # type: Bogus[str] # Fully qualified name of the class defs = None # type: Block - type_vars = None # type: List[mypy.types.TypeVarDef] + type_vars = None # type: List[mypy.types.TypeVarType] # Base class expressions (not semantically analyzed -- can be arbitrary expressions) base_type_exprs = None # type: List[Expression] # Special base classes like Generic[...] get moved here during semantic analysis @@ -931,7 +931,7 @@ class ClassDef(Statement): def __init__(self, name: str, defs: 'Block', - type_vars: Optional[List['mypy.types.TypeVarDef']] = None, + type_vars: Optional[List['mypy.types.TypeVarType']] = None, base_type_exprs: Optional[List[Expression]] = None, metaclass: Optional[Expression] = None, keywords: Optional[List[Tuple[str, Expression]]] = None) -> None: @@ -966,7 +966,7 @@ def deserialize(self, data: JsonDict) -> 'ClassDef': assert data['.class'] == 'ClassDef' res = ClassDef(data['name'], Block([]), - [mypy.types.TypeVarDef.deserialize(v) for v in data['type_vars']], + [mypy.types.TypeVarType.deserialize(v) for v in data['type_vars']], ) res.fullname = data['fullname'] return res diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 5fd2dde01a03..cbb993e465ee 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -21,7 +21,7 @@ deserialize_and_fixup_type ) from mypy.types import ( - Type, AnyType, TypeOfAny, CallableType, NoneType, TypeVarDef, TypeVarType, + Type, AnyType, TypeOfAny, CallableType, NoneType, TypeVarType, TypeVarType, Overloaded, UnionType, FunctionLike, get_proper_type ) from mypy.typeops import make_simplified_union, map_type_from_supertype @@ -648,16 +648,15 @@ def _add_order(ctx: 'mypy.plugin.ClassDefContext', adder: 'MethodAdder') -> None # AT = TypeVar('AT') # def __lt__(self: AT, other: AT) -> bool # This way comparisons with subclasses will work correctly. - tvd = TypeVarDef(SELF_TVAR_NAME, ctx.cls.info.fullname + '.' + SELF_TVAR_NAME, + tvd = TypeVarType(SELF_TVAR_NAME, ctx.cls.info.fullname + '.' + SELF_TVAR_NAME, -1, [], object_type) - tvd_type = TypeVarType(tvd) self_tvar_expr = TypeVarExpr(SELF_TVAR_NAME, ctx.cls.info.fullname + '.' + SELF_TVAR_NAME, [], object_type) ctx.cls.info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) - args = [Argument(Var('other', tvd_type), tvd_type, None, ARG_POS)] + args = [Argument(Var('other', tvd), tvd, None, ARG_POS)] for method in ['__lt__', '__le__', '__gt__', '__ge__']: - adder.add_method(method, args, bool_type, self_type=tvd_type, tvd=tvd) + adder.add_method(method, args, bool_type, self_type=tvd, tvd=tvd) def _make_frozen(ctx: 'mypy.plugin.ClassDefContext', attributes: List[Attribute]) -> None: @@ -724,7 +723,7 @@ def __init__(self, ctx: 'mypy.plugin.ClassDefContext') -> None: def add_method(self, method_name: str, args: List[Argument], ret_type: Type, self_type: Optional[Type] = None, - tvd: Optional[TypeVarDef] = None) -> None: + tvd: Optional[TypeVarType] = None) -> None: """Add a method: def (self, ) -> ): ... to info. self_type: The type to use for the self argument or None to use the inferred self type. diff --git a/mypy/plugins/common.py b/mypy/plugins/common.py index 536022a1e09e..b2769c3014f5 100644 --- a/mypy/plugins/common.py +++ b/mypy/plugins/common.py @@ -7,7 +7,7 @@ from mypy.plugin import ClassDefContext, SemanticAnalyzerPluginInterface from mypy.semanal import set_callable_name from mypy.types import ( - CallableType, Overloaded, Type, TypeVarDef, deserialize_type, get_proper_type, + CallableType, Overloaded, Type, TypeVarType, deserialize_type, get_proper_type, ) from mypy.typevars import fill_typevars from mypy.util import get_unique_redefinition_name @@ -88,7 +88,7 @@ def add_method( args: List[Argument], return_type: Type, self_type: Optional[Type] = None, - tvar_def: Optional[TypeVarDef] = None, + tvar_def: Optional[TypeVarType] = None, ) -> None: """ Adds a new method to a class. @@ -109,7 +109,7 @@ def add_method_to_class( args: List[Argument], return_type: Type, self_type: Optional[Type] = None, - tvar_def: Optional[TypeVarDef] = None, + tvar_def: Optional[TypeVarType] = None, ) -> None: """Adds a new method to a class definition. """ diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 5765e0599759..939753c8897c 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -13,7 +13,7 @@ add_method, _get_decorator_bool_argument, deserialize_and_fixup_type, ) from mypy.typeops import map_type_from_supertype -from mypy.types import Type, Instance, NoneType, TypeVarDef, TypeVarType, get_proper_type +from mypy.types import Type, Instance, NoneType, TypeVarType, TypeVarType, get_proper_type from mypy.server.trigger import make_wildcard_trigger # The set of decorators that generate dataclasses. @@ -143,12 +143,11 @@ def transform(self) -> None: # Like for __eq__ and __ne__, we want "other" to match # the self type. obj_type = ctx.api.named_type('__builtins__.object') - order_tvar_def = TypeVarDef(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, + order_tvar_def = TypeVarType(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, -1, [], obj_type) - order_other_type = TypeVarType(order_tvar_def) order_return_type = ctx.api.named_type('__builtins__.bool') order_args = [ - Argument(Var('other', order_other_type), order_other_type, None, ARG_POS) + Argument(Var('other', order_tvar_def), order_tvar_def, None, ARG_POS) ] existing_method = info.get(method_name) @@ -164,7 +163,7 @@ def transform(self) -> None: method_name, args=order_args, return_type=order_return_type, - self_type=order_other_type, + self_type=order_tvar_def, tvar_def=order_tvar_def, ) diff --git a/mypy/plugins/default.py b/mypy/plugins/default.py index 3621e4e4de7a..7d40aca67218 100644 --- a/mypy/plugins/default.py +++ b/mypy/plugins/default.py @@ -10,7 +10,7 @@ from mypy.plugins.common import try_getting_str_literals from mypy.types import ( Type, Instance, AnyType, TypeOfAny, CallableType, NoneType, TypedDictType, - TypeVarDef, TypeVarType, TPDICT_FB_NAMES, get_proper_type, LiteralType + TypeVarType, TypeVarType, TPDICT_FB_NAMES, get_proper_type, LiteralType ) from mypy.subtypes import is_subtype from mypy.typeops import make_simplified_union @@ -215,8 +215,8 @@ def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType: # Tweak the signature to include the value type as context. It's # only needed for type inference since there's a union with a type # variable that accepts everything. - assert isinstance(signature.variables[0], TypeVarDef) - tv = TypeVarType(signature.variables[0]) + tv = signature.variables[0] + assert isinstance(tv, TypeVarType) return signature.copy_modified( arg_types=[signature.arg_types[0], make_simplified_union([value_type, tv])], @@ -280,8 +280,8 @@ def typed_dict_pop_signature_callback(ctx: MethodSigContext) -> CallableType: # Tweak the signature to include the value type as context. It's # only needed for type inference since there's a union with a type # variable that accepts everything. - assert isinstance(signature.variables[0], TypeVarDef) - tv = TypeVarType(signature.variables[0]) + tv = signature.variables[0] + assert isinstance(tv, TypeVarType) typ = make_simplified_union([value_type, tv]) return signature.copy_modified( arg_types=[str_type, typ], diff --git a/mypy/semanal.py b/mypy/semanal.py index 42353d10a5e6..e94a9c2d6d41 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -88,7 +88,7 @@ from mypy.errorcodes import ErrorCode from mypy import message_registry, errorcodes as codes from mypy.types import ( - FunctionLike, UnboundType, TypeVarDef, TupleType, UnionType, StarType, + FunctionLike, UnboundType, TypeVarType, TupleType, UnionType, StarType, CallableType, Overloaded, Instance, Type, AnyType, LiteralType, LiteralValue, TypeTranslator, TypeOfAny, TypeType, NoneType, PlaceholderType, TPDICT_NAMES, ProperType, get_proper_type, get_proper_types, TypeAliasType) @@ -1232,7 +1232,7 @@ def clean_up_bases_and_infer_type_variables( defn: ClassDef, base_type_exprs: List[Expression], context: Context) -> Tuple[List[Expression], - List[TypeVarDef], + List[TypeVarType], bool]: """Remove extra base classes such as Generic and infer type vars. @@ -1293,10 +1293,10 @@ class Foo(Bar, Generic[T]): ... # grained incremental mode. defn.removed_base_type_exprs.append(defn.base_type_exprs[i]) del base_type_exprs[i] - tvar_defs = [] # type: List[TypeVarDef] + tvar_defs = [] # type: List[TypeVarType] for name, tvar_expr in declared_tvars: tvar_def = self.tvar_scope.bind_new(name, tvar_expr) - assert isinstance(tvar_def, TypeVarDef), ( + assert isinstance(tvar_def, TypeVarType), ( "mypy does not currently support ParamSpec use in generic classes" ) tvar_defs.append(tvar_def) diff --git a/mypy/semanal_namedtuple.py b/mypy/semanal_namedtuple.py index 0067fba22322..2297f28baab6 100644 --- a/mypy/semanal_namedtuple.py +++ b/mypy/semanal_namedtuple.py @@ -8,7 +8,7 @@ from typing_extensions import Final from mypy.types import ( - Type, TupleType, AnyType, TypeOfAny, TypeVarDef, CallableType, TypeType, TypeVarType, + Type, TupleType, AnyType, TypeOfAny, TypeVarType, CallableType, TypeType, TypeVarType, UnboundType, ) from mypy.semanal_shared import ( @@ -421,9 +421,9 @@ def add_field(var: Var, is_initialized_in_class: bool = False, add_field(Var('__annotations__', ordereddictype), is_initialized_in_class=True) add_field(Var('__doc__', strtype), is_initialized_in_class=True) - tvd = TypeVarDef(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, + tvd = TypeVarType(SELF_TVAR_NAME, info.fullname + '.' + SELF_TVAR_NAME, -1, [], info.tuple_type) - selftype = TypeVarType(tvd) + selftype = tvd def add_method(funcname: str, ret: Type, diff --git a/mypy/server/astdiff.py b/mypy/server/astdiff.py index 9893092882b5..c1c8d67d5a45 100644 --- a/mypy/server/astdiff.py +++ b/mypy/server/astdiff.py @@ -213,7 +213,7 @@ def snapshot_definition(node: Optional[SymbolNode], # x: C[str] <- this is invalid, and needs to be re-checked if `T` changes. # An alternative would be to create both deps: <...> -> C, and <...> -> , # but this currently seems a bit ad hoc. - tuple(snapshot_type(TypeVarType(tdef)) for tdef in node.defn.type_vars), + tuple(snapshot_type(tdef) for tdef in node.defn.type_vars), [snapshot_type(base) for base in node.bases], snapshot_optional_type(node._promote)) prefix = node.fullname diff --git a/mypy/server/astmerge.py b/mypy/server/astmerge.py index 1c411886ac7d..6543859cbded 100644 --- a/mypy/server/astmerge.py +++ b/mypy/server/astmerge.py @@ -58,7 +58,7 @@ from mypy.types import ( Type, SyntheticTypeVisitor, Instance, AnyType, NoneType, CallableType, ErasedType, DeletedType, TupleType, TypeType, TypeVarType, TypedDictType, UnboundType, UninhabitedType, UnionType, - Overloaded, TypeVarDef, TypeList, CallableArgument, EllipsisType, StarType, LiteralType, + Overloaded, TypeVarType, TypeList, CallableArgument, EllipsisType, StarType, LiteralType, RawExpressionType, PartialType, PlaceholderType, TypeAliasType ) from mypy.util import get_prefix, replace_object_state @@ -188,7 +188,7 @@ def process_base_func(self, node: FuncBase) -> None: # Unanalyzed types can have AST node references self.fixup_type(node.unanalyzed_type) - def process_type_var_def(self, tv: TypeVarDef) -> None: + def process_type_var_def(self, tv: TypeVarType) -> None: for value in tv.values: self.fixup_type(value) self.fixup_type(tv.upper_bound) @@ -370,7 +370,7 @@ def visit_callable_type(self, typ: CallableType) -> None: if typ.fallback is not None: typ.fallback.accept(self) for tv in typ.variables: - if isinstance(tv, TypeVarDef): + if isinstance(tv, TypeVarType): tv.upper_bound.accept(self) for value in tv.values: value.accept(self) diff --git a/mypy/test/testtypes.py b/mypy/test/testtypes.py index c65bfc7b9418..0f5ef6bc64bf 100644 --- a/mypy/test/testtypes.py +++ b/mypy/test/testtypes.py @@ -10,7 +10,7 @@ from mypy.sametypes import is_same_type from mypy.indirection import TypeIndirectionVisitor from mypy.types import ( - UnboundType, AnyType, CallableType, TupleType, TypeVarDef, Type, Instance, NoneType, + UnboundType, AnyType, CallableType, TupleType, TypeVarType, Type, Instance, NoneType, Overloaded, TypeType, UnionType, UninhabitedType, TypeVarId, TypeOfAny, LiteralType, get_proper_type ) @@ -78,18 +78,18 @@ def test_tuple_type(self) -> None: self.fx.std_tuple)), 'Tuple[X?, Any]') def test_type_variable_binding(self) -> None: - assert_equal(str(TypeVarDef('X', 'X', 1, [], self.fx.o)), 'X') - assert_equal(str(TypeVarDef('X', 'X', 1, [self.x, self.y], self.fx.o)), + assert_equal(str(TypeVarType('X', 'X', 1, [], self.fx.o)), 'X') + assert_equal(str(TypeVarType('X', 'X', 1, [self.x, self.y], self.fx.o)), 'X in (X?, Y?)') def test_generic_function_type(self) -> None: c = CallableType([self.x, self.y], [ARG_POS, ARG_POS], [None, None], self.y, self.function, name=None, - variables=[TypeVarDef('X', 'X', -1, [], self.fx.o)]) + variables=[TypeVarType('X', 'X', -1, [], self.fx.o)]) assert_equal(str(c), 'def [X] (X?, Y?) -> Y?') - v = [TypeVarDef('Y', 'Y', -1, [], self.fx.o), - TypeVarDef('X', 'X', -2, [], self.fx.o)] + v = [TypeVarType('Y', 'Y', -1, [], self.fx.o), + TypeVarType('X', 'X', -2, [], self.fx.o)] c2 = CallableType([], [], [], NoneType(), self.function, name=None, variables=v) assert_equal(str(c2), 'def [Y, X] ()') @@ -461,10 +461,10 @@ def callable(self, vars: List[str], *a: Type) -> CallableType: argument types a1, ... an and return type r and type arguments vars. """ - tv = [] # type: List[TypeVarDef] + tv = [] # type: List[TypeVarType] n = -1 for v in vars: - tv.append(TypeVarDef(v, v, n, [], self.fx.o)) + tv.append(TypeVarType(v, v, n, [], self.fx.o)) n -= 1 return CallableType(list(a[:-1]), [ARG_POS] * (len(a) - 1), diff --git a/mypy/test/typefixture.py b/mypy/test/typefixture.py index b29f7164c911..99b43239483b 100644 --- a/mypy/test/typefixture.py +++ b/mypy/test/typefixture.py @@ -6,7 +6,7 @@ from typing import List, Optional, Tuple from mypy.types import ( - Type, TypeVarType, AnyType, NoneType, Instance, CallableType, TypeVarDef, TypeType, + Type, TypeVarType, AnyType, NoneType, Instance, CallableType, TypeVarType, TypeType, UninhabitedType, TypeOfAny, TypeAliasType, UnionType ) from mypy.nodes import ( @@ -30,7 +30,7 @@ def __init__(self, variance: int = COVARIANT) -> None: def make_type_var(name: str, id: int, values: List[Type], upper_bound: Type, variance: int) -> TypeVarType: - return TypeVarType(TypeVarDef(name, name, id, values, upper_bound, variance)) + return TypeVarType(name, name, id, values, upper_bound, variance) self.t = make_type_var('T', 1, [], self.o, variance) # T`1 (type variable) self.tf = make_type_var('T', -1, [], self.o, variance) # T`-1 (type variable) @@ -214,13 +214,13 @@ def make_type_info(self, name: str, module_name = '__main__' if typevars: - v = [] # type: List[TypeVarDef] + v = [] # type: List[TypeVarType] for id, n in enumerate(typevars, 1): if variances: variance = variances[id - 1] else: variance = COVARIANT - v.append(TypeVarDef(n, n, id, [], self.o, variance=variance)) + v.append(TypeVarType(n, n, id, [], self.o, variance=variance)) class_def.type_vars = v info = TypeInfo(SymbolTable(), class_def, module_name) diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py index 4c7a165036a2..992a9782d882 100644 --- a/mypy/tvar_scope.py +++ b/mypy/tvar_scope.py @@ -1,5 +1,5 @@ from typing import Optional, Dict, Union -from mypy.types import TypeVarLikeDef, TypeVarDef, ParamSpecDef +from mypy.types import TypeVarLikeDef, TypeVarType, ParamSpecDef from mypy.nodes import ParamSpecExpr, TypeVarExpr, TypeVarLikeExpr, SymbolTableNode @@ -63,7 +63,7 @@ def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeDef: self.func_id -= 1 i = self.func_id if isinstance(tvar_expr, TypeVarExpr): - tvar_def = TypeVarDef( + tvar_def = TypeVarType( name, tvar_expr.fullname, i, diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 8d86fe199ad3..87e371f43e87 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -13,7 +13,7 @@ from mypy.options import Options from mypy.types import ( Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance, AnyType, - CallableType, NoneType, ErasedType, DeletedType, TypeList, TypeVarDef, SyntheticTypeVisitor, + CallableType, NoneType, ErasedType, DeletedType, TypeList, TypeVarType, SyntheticTypeVisitor, StarType, PartialType, EllipsisType, UninhabitedType, TypeType, CallableArgument, TypeQuery, union_items, TypeOfAny, LiteralType, RawExpressionType, PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeDef, ParamSpecDef @@ -220,7 +220,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) ' to define generic alias'.format(t.name), t) return AnyType(TypeOfAny.from_error) if isinstance(sym.node, TypeVarExpr) and tvar_def is not None: - assert isinstance(tvar_def, TypeVarDef) + assert isinstance(tvar_def, TypeVarType) if len(t.args) > 0: self.fail('Type variable "{}" used with arguments'.format(t.name), t) return TypeVarType(tvar_def, t.line) @@ -961,8 +961,8 @@ def anal_type(self, t: Type, nested: bool = True) -> Type: self.nesting_level -= 1 def anal_var_def(self, var_def: TypeVarLikeDef) -> TypeVarLikeDef: - if isinstance(var_def, TypeVarDef): - return TypeVarDef( + if isinstance(var_def, TypeVarType): + return TypeVarType( var_def.name, var_def.fullname, var_def.id.raw_id, diff --git a/mypy/typeops.py b/mypy/typeops.py index 3b5ca73f8713..4534d38d9228 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -11,7 +11,7 @@ import sys from mypy.types import ( - TupleType, Instance, FunctionLike, Type, CallableType, TypeVarDef, TypeVarLikeDef, Overloaded, + TupleType, Instance, FunctionLike, Type, CallableType, TypeVarType, TypeVarLikeDef, Overloaded, TypeVarType, UninhabitedType, FormalArgument, UnionType, NoneType, TypedDictType, AnyType, TypeOfAny, TypeType, ProperType, LiteralType, get_proper_type, get_proper_types, copy_type, TypeAliasType, TypeQuery @@ -483,7 +483,7 @@ def true_or_false(t: Type) -> ProperType: def erase_def_to_union_or_bound(tdef: TypeVarLikeDef) -> Type: # TODO(shantanu): fix for ParamSpecDef - assert isinstance(tdef, TypeVarDef) + assert isinstance(tdef, TypeVarType) if tdef.values: return make_simplified_union(tdef.values) else: diff --git a/mypy/types.py b/mypy/types.py index 9424474a1066..8c58809ea7ab 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -361,7 +361,7 @@ def deserialize(cls, data: JsonDict) -> 'TypeVarLikeDef': raise NotImplementedError -class TypeVarDef(TypeVarLikeDef): +class TypeVarType(TypeVarLikeDef): """Definition of a single type variable.""" values = None # type: List[Type] # Value restriction, empty list if no restriction upper_bound = None # type: Type @@ -377,9 +377,9 @@ def __init__(self, name: str, fullname: str, id: Union[TypeVarId, int], values: self.variance = variance @staticmethod - def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef': + def new_unification_variable(old: 'TypeVarType') -> 'TypeVarType': new_id = TypeVarId.new(meta_level=1) - return TypeVarDef(old.name, old.fullname, new_id, old.values, + return TypeVarType(old.name, old.fullname, new_id, old.values, old.upper_bound, old.variance, old.line, old.column) def accept(self, visitor: 'TypeVisitor[T]') -> T: @@ -395,7 +395,7 @@ def __eq__(self, other: object) -> bool: def serialize(self) -> JsonDict: assert not self.id.is_meta_var() - return {'.class': 'TypeVarDef', + return {'.class': 'TypeVarType', 'name': self.name, 'fullname': self.fullname, 'id': self.id.raw_id, @@ -405,9 +405,9 @@ def serialize(self) -> JsonDict: } @classmethod - def deserialize(cls, data: JsonDict) -> 'TypeVarDef': - assert data['.class'] == 'TypeVarDef' - return TypeVarDef(data['name'], + def deserialize(cls, data: JsonDict) -> 'TypeVarType': + assert data['.class'] == 'TypeVarType' + return TypeVarType(data['name'], data['fullname'], data['id'], [deserialize_type(v) for v in data['values']], @@ -1248,7 +1248,7 @@ def deserialize(cls, data: JsonDict) -> 'CallableType': deserialize_type(data['ret_type']), Instance.deserialize(data['fallback']), name=data['name'], - variables=[TypeVarDef.deserialize(v) for v in data['variables']], + variables=[TypeVarType.deserialize(v) for v in data['variables']], is_ellipsis_args=data['is_ellipsis_args'], implicit=data['implicit'], bound_args=[(None if t is None else deserialize_type(t)) @@ -2074,8 +2074,8 @@ def visit_callable_type(self, t: CallableType) -> str: if t.variables: vs = [] for var in t.variables: - if isinstance(var, TypeVarDef): - # We reimplement TypeVarDef.__repr__ here in order to support id_mapper. + if isinstance(var, TypeVarType): + # We reimplement TypeVarType.__repr__ here in order to support id_mapper. if var.values: vals = '({})'.format(', '.join(val.accept(self) for val in var.values)) vs.append('{} in {}'.format(var.name, vals)) diff --git a/mypy/typevars.py b/mypy/typevars.py index 113569874ceb..02045058f524 100644 --- a/mypy/typevars.py +++ b/mypy/typevars.py @@ -14,7 +14,7 @@ def fill_typevars(typ: TypeInfo) -> Union[Instance, TupleType]: tv = [] # type: List[Type] # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars? for i in range(len(typ.defn.type_vars)): - tv.append(TypeVarType(typ.defn.type_vars[i])) + tv.append(typ.defn.type_vars[i]) inst = Instance(typ, tv) if typ.tuple_type is None: return inst From 323eb8ff82a556d4166c136a347310cb8ed91b83 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Mon, 18 Jan 2021 19:16:28 -0800 Subject: [PATCH 03/11] fix line number --- mypy/typeanal.py | 5 ++++- mypy/typevars.py | 11 ++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 87e371f43e87..f56b5dc263de 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -223,7 +223,10 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) assert isinstance(tvar_def, TypeVarType) if len(t.args) > 0: self.fail('Type variable "{}" used with arguments'.format(t.name), t) - return TypeVarType(tvar_def, t.line) + return TypeVarType( + tvar_def.name, tvar_def.fullname, tvar_def.id, tvar_def.values, + tvar_def.upper_bound, tvar_def.variance, line=t.line, column=t.column, + ) special = self.try_analyze_special_unbound_type(t, fullname) if special is not None: return special diff --git a/mypy/typevars.py b/mypy/typevars.py index 02045058f524..1e6475480542 100644 --- a/mypy/typevars.py +++ b/mypy/typevars.py @@ -11,11 +11,16 @@ def fill_typevars(typ: TypeInfo) -> Union[Instance, TupleType]: For a generic G type with parameters T1, .., Tn, return G[T1, ..., Tn]. """ - tv = [] # type: List[Type] + tvs = [] # type: List[Type] # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars? for i in range(len(typ.defn.type_vars)): - tv.append(typ.defn.type_vars[i]) - inst = Instance(typ, tv) + tv = typ.defn.type_vars[i] + tv = TypeVarType( + tv.name, tv.fullname, tv.id, tv.values, + tv.upper_bound, tv.variance, line=-1, column=-1, + ) + tvs.append(tv) + inst = Instance(typ, tvs) if typ.tuple_type is None: return inst return typ.tuple_type.copy_modified(fallback=inst) From 14e22e0b2a25ab848e2122118fd5639d9752f183 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sat, 23 Jan 2021 16:13:28 -0800 Subject: [PATCH 04/11] fix tests --- mypy/test/testtypes.py | 4 +- test-data/unit/semanal-abstractclasses.test | 2 +- test-data/unit/semanal-typealiases.test | 2 +- test-data/unit/semanal-types.test | 56 ++++++++++----------- 4 files changed, 32 insertions(+), 32 deletions(-) diff --git a/mypy/test/testtypes.py b/mypy/test/testtypes.py index 0f5ef6bc64bf..3f89b8688218 100644 --- a/mypy/test/testtypes.py +++ b/mypy/test/testtypes.py @@ -78,9 +78,9 @@ def test_tuple_type(self) -> None: self.fx.std_tuple)), 'Tuple[X?, Any]') def test_type_variable_binding(self) -> None: - assert_equal(str(TypeVarType('X', 'X', 1, [], self.fx.o)), 'X') + assert_equal(str(TypeVarType('X', 'X', 1, [], self.fx.o)), 'X`1') assert_equal(str(TypeVarType('X', 'X', 1, [self.x, self.y], self.fx.o)), - 'X in (X?, Y?)') + 'X`1') def test_generic_function_type(self) -> None: c = CallableType([self.x, self.y], [ARG_POS, ARG_POS], [None, None], diff --git a/test-data/unit/semanal-abstractclasses.test b/test-data/unit/semanal-abstractclasses.test index dfd5dee1554a..b0cb00e82106 100644 --- a/test-data/unit/semanal-abstractclasses.test +++ b/test-data/unit/semanal-abstractclasses.test @@ -79,7 +79,7 @@ MypyFile:1( ClassDef:4( A TypeVars( - T) + T`1) Decorator:5( Var(f) FuncDef:6( diff --git a/test-data/unit/semanal-typealiases.test b/test-data/unit/semanal-typealiases.test index 0f16754e0959..debc7ecdf722 100644 --- a/test-data/unit/semanal-typealiases.test +++ b/test-data/unit/semanal-typealiases.test @@ -219,7 +219,7 @@ MypyFile:1( ClassDef:3( G TypeVars( - T) + T`1) PassStmt:3()) AssignmentStmt:4( NameExpr(A* [__main__.A]) diff --git a/test-data/unit/semanal-types.test b/test-data/unit/semanal-types.test index 0c0354a79aeb..e56bd612ca12 100644 --- a/test-data/unit/semanal-types.test +++ b/test-data/unit/semanal-types.test @@ -188,7 +188,7 @@ MypyFile:1( ClassDef:5( A TypeVars( - t) + t`1) PassStmt:5()) ClassDef:6( B @@ -221,8 +221,8 @@ MypyFile:1( ClassDef:4( A TypeVars( - t - s) + t`1 + s`2) PassStmt:4()) ClassDef:5( B @@ -284,7 +284,7 @@ MypyFile:1( ClassDef:4( d TypeVars( - t) + t`1) PassStmt:4()) ExpressionStmt:5( CastExpr:5( @@ -348,8 +348,8 @@ MypyFile:1( ClassDef:4( C TypeVars( - t - s) + t`1 + s`2) PassStmt:4()) ExpressionStmt:5( CastExpr:5( @@ -450,7 +450,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) FuncDef:4( f @@ -476,7 +476,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) FuncDef:4( f @@ -500,7 +500,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) FuncDef:4( f @@ -524,7 +524,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) FuncDef:4( f @@ -603,7 +603,7 @@ MypyFile:1( ClassDef:5( c TypeVars( - t) + t`1) FuncDef:6( f Args( @@ -632,8 +632,8 @@ MypyFile:1( ClassDef:6( c TypeVars( - t - s) + t`1 + s`2) FuncDef:7( f Args( @@ -657,12 +657,12 @@ MypyFile:1( ClassDef:3( d TypeVars( - t) + t`1) PassStmt:3()) ClassDef:4( c TypeVars( - t) + t`1) BaseType( __main__.d[t`1]) PassStmt:4())) @@ -876,8 +876,8 @@ MypyFile:1( ClassDef:4( A TypeVars( - t - s) + t`1 + s`2) PassStmt:4()) AssignmentStmt:5( NameExpr(x [__main__.x]) @@ -902,12 +902,12 @@ MypyFile:1( ClassDef:4( B TypeVars( - s) + s`1) PassStmt:4()) ClassDef:5( A TypeVars( - t) + t`1) BaseType( __main__.B[Any]) PassStmt:5())) @@ -926,7 +926,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) AssignmentStmt:4( NameExpr(x* [__main__.x]) @@ -955,8 +955,8 @@ MypyFile:1( ClassDef:4( A TypeVars( - t - s) + t`1 + s`2) PassStmt:4()) AssignmentStmt:5( NameExpr(x* [__main__.x]) @@ -1009,7 +1009,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - t) + t`1) PassStmt:3()) ExpressionStmt:4( CallExpr:4( @@ -1051,7 +1051,7 @@ MypyFile:1( ClassDef:4( A TypeVars( - T) + T`1) PassStmt:4())) [case testQualifiedTypevar] @@ -1149,7 +1149,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - T) + T`1) AssignmentStmt:4( NameExpr(y [m]) NameExpr(None [builtins.None]) @@ -1172,7 +1172,7 @@ MypyFile:1( ClassDef:3( A TypeVars( - _m.T) + _m.T`1) AssignmentStmt:4( NameExpr(a [m]) NameExpr(None [builtins.None]) @@ -1332,7 +1332,7 @@ MypyFile:1( ClassDef:3( C TypeVars( - T in (builtins.int, builtins.str)) + T`1) PassStmt:3())) [case testGenericFunctionWithBound] @@ -1368,7 +1368,7 @@ MypyFile:1( ClassDef:3( C TypeVars( - T <: builtins.int) + T`1) PassStmt:3())) [case testSimpleDucktypeDecorator] From 0523b5b35ff44a14e6ade333a0aa1b491a595bab Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sat, 23 Jan 2021 16:38:38 -0800 Subject: [PATCH 05/11] fix imports --- mypy/applytype.py | 2 +- mypy/checker.py | 2 +- mypy/checkexpr.py | 2 +- mypy/fixup.py | 2 +- mypy/plugins/attrs.py | 2 +- mypy/plugins/dataclasses.py | 2 +- mypy/semanal_namedtuple.py | 2 +- mypy/server/astmerge.py | 2 +- mypy/test/typefixture.py | 2 +- mypy/typeanal.py | 2 +- mypy/typeops.py | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/mypy/applytype.py b/mypy/applytype.py index 6c0a1521909d..e571a506c5a0 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -5,7 +5,7 @@ from mypy.expandtype import expand_type from mypy.types import ( Type, TypeVarId, TypeVarType, CallableType, AnyType, PartialType, get_proper_types, - TypeVarType, TypeVarLikeDef, ProperType + TypeVarLikeDef, ProperType ) from mypy.nodes import Context diff --git a/mypy/checker.py b/mypy/checker.py index 1ef80faee88f..18bb6b7a174d 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -32,7 +32,7 @@ from mypy.types import ( Type, AnyType, CallableType, FunctionLike, Overloaded, TupleType, TypedDictType, Instance, NoneType, strip_type, TypeType, TypeOfAny, - UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarType, + UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType, is_named_instance, union_items, TypeQuery, LiteralType, is_optional, remove_optional, TypeTranslator, StarType, get_proper_type, ProperType, get_proper_types, is_literal_type, TypeAliasType, TypeGuardType) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index f85c2e211e44..ac378313f487 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -15,7 +15,7 @@ ) from mypy.types import ( Type, AnyType, CallableType, Overloaded, NoneType, TypeVarType, TypeGuardType, - TupleType, TypedDictType, Instance, TypeVarType, ErasedType, UnionType, + TupleType, TypedDictType, Instance, ErasedType, UnionType, PartialType, DeletedType, UninhabitedType, TypeType, TypeOfAny, LiteralType, LiteralValue, is_named_instance, FunctionLike, StarType, is_optional, remove_optional, is_generic_instance, get_proper_type, ProperType, diff --git a/mypy/fixup.py b/mypy/fixup.py index 11bb1b6f2624..60cc43327e29 100644 --- a/mypy/fixup.py +++ b/mypy/fixup.py @@ -11,7 +11,7 @@ from mypy.types import ( CallableType, Instance, Overloaded, TupleType, TypedDictType, TypeVarType, UnboundType, UnionType, TypeVisitor, LiteralType, - TypeType, NOT_READY, TypeAliasType, AnyType, TypeOfAny, TypeVarType + TypeType, NOT_READY, TypeAliasType, AnyType, TypeOfAny ) from mypy.visitor import NodeVisitor from mypy.lookup import lookup_fully_qualified diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index cbb993e465ee..831ee8ec52d6 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -21,7 +21,7 @@ deserialize_and_fixup_type ) from mypy.types import ( - Type, AnyType, TypeOfAny, CallableType, NoneType, TypeVarType, TypeVarType, + Type, AnyType, TypeOfAny, CallableType, NoneType, TypeVarType, Overloaded, UnionType, FunctionLike, get_proper_type ) from mypy.typeops import make_simplified_union, map_type_from_supertype diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 939753c8897c..34c7e6bbd100 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -13,7 +13,7 @@ add_method, _get_decorator_bool_argument, deserialize_and_fixup_type, ) from mypy.typeops import map_type_from_supertype -from mypy.types import Type, Instance, NoneType, TypeVarType, TypeVarType, get_proper_type +from mypy.types import Type, Instance, NoneType, TypeVarType, get_proper_type from mypy.server.trigger import make_wildcard_trigger # The set of decorators that generate dataclasses. diff --git a/mypy/semanal_namedtuple.py b/mypy/semanal_namedtuple.py index 2297f28baab6..c03f903171b7 100644 --- a/mypy/semanal_namedtuple.py +++ b/mypy/semanal_namedtuple.py @@ -8,7 +8,7 @@ from typing_extensions import Final from mypy.types import ( - Type, TupleType, AnyType, TypeOfAny, TypeVarType, CallableType, TypeType, TypeVarType, + Type, TupleType, AnyType, TypeOfAny, CallableType, TypeType, TypeVarType, UnboundType, ) from mypy.semanal_shared import ( diff --git a/mypy/server/astmerge.py b/mypy/server/astmerge.py index 6543859cbded..0654032148be 100644 --- a/mypy/server/astmerge.py +++ b/mypy/server/astmerge.py @@ -57,7 +57,7 @@ from mypy.traverser import TraverserVisitor from mypy.types import ( Type, SyntheticTypeVisitor, Instance, AnyType, NoneType, CallableType, ErasedType, DeletedType, - TupleType, TypeType, TypeVarType, TypedDictType, UnboundType, UninhabitedType, UnionType, + TupleType, TypeType, TypedDictType, UnboundType, UninhabitedType, UnionType, Overloaded, TypeVarType, TypeList, CallableArgument, EllipsisType, StarType, LiteralType, RawExpressionType, PartialType, PlaceholderType, TypeAliasType ) diff --git a/mypy/test/typefixture.py b/mypy/test/typefixture.py index 99b43239483b..173b829197e3 100644 --- a/mypy/test/typefixture.py +++ b/mypy/test/typefixture.py @@ -6,7 +6,7 @@ from typing import List, Optional, Tuple from mypy.types import ( - Type, TypeVarType, AnyType, NoneType, Instance, CallableType, TypeVarType, TypeType, + Type, AnyType, NoneType, Instance, CallableType, TypeVarType, TypeType, UninhabitedType, TypeOfAny, TypeAliasType, UnionType ) from mypy.nodes import ( diff --git a/mypy/typeanal.py b/mypy/typeanal.py index f56b5dc263de..bb0adb280bec 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -13,7 +13,7 @@ from mypy.options import Options from mypy.types import ( Type, UnboundType, TypeVarType, TupleType, TypedDictType, UnionType, Instance, AnyType, - CallableType, NoneType, ErasedType, DeletedType, TypeList, TypeVarType, SyntheticTypeVisitor, + CallableType, NoneType, ErasedType, DeletedType, TypeList, SyntheticTypeVisitor, StarType, PartialType, EllipsisType, UninhabitedType, TypeType, CallableArgument, TypeQuery, union_items, TypeOfAny, LiteralType, RawExpressionType, PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeDef, ParamSpecDef diff --git a/mypy/typeops.py b/mypy/typeops.py index 4534d38d9228..11a902917f70 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -11,7 +11,7 @@ import sys from mypy.types import ( - TupleType, Instance, FunctionLike, Type, CallableType, TypeVarType, TypeVarLikeDef, Overloaded, + TupleType, Instance, FunctionLike, Type, CallableType, TypeVarLikeDef, Overloaded, TypeVarType, UninhabitedType, FormalArgument, UnionType, NoneType, TypedDictType, AnyType, TypeOfAny, TypeType, ProperType, LiteralType, get_proper_type, get_proper_types, copy_type, TypeAliasType, TypeQuery From 8c685cd25954ac53eac73c4336c4288380080c44 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sat, 23 Jan 2021 16:39:16 -0800 Subject: [PATCH 06/11] fix flake8 --- mypy/types.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/mypy/types.py b/mypy/types.py index 8c58809ea7ab..ea05d0338e86 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -407,13 +407,14 @@ def serialize(self) -> JsonDict: @classmethod def deserialize(cls, data: JsonDict) -> 'TypeVarType': assert data['.class'] == 'TypeVarType' - return TypeVarType(data['name'], - data['fullname'], - data['id'], - [deserialize_type(v) for v in data['values']], - deserialize_type(data['upper_bound']), - data['variance'], - ) + return TypeVarType( + data['name'], + data['fullname'], + data['id'], + [deserialize_type(v) for v in data['values']], + deserialize_type(data['upper_bound']), + data['variance'], + ) class ParamSpecDef(TypeVarLikeDef): From afea1963869e965d53e5b56822f2c54326dbb1cb Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sat, 23 Jan 2021 19:21:03 -0800 Subject: [PATCH 07/11] typevarlikedef -> typevarliketype --- mypy/applytype.py | 4 ++-- mypy/checkmember.py | 6 +++--- mypy/messages.py | 2 +- mypy/tvar_scope.py | 14 +++++++------- mypy/type_visitor.py | 4 ++-- mypy/typeanal.py | 10 +++++----- mypy/typeops.py | 8 ++++---- mypy/types.py | 14 +++++++------- 8 files changed, 31 insertions(+), 31 deletions(-) diff --git a/mypy/applytype.py b/mypy/applytype.py index e571a506c5a0..915352000746 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -5,13 +5,13 @@ from mypy.expandtype import expand_type from mypy.types import ( Type, TypeVarId, TypeVarType, CallableType, AnyType, PartialType, get_proper_types, - TypeVarLikeDef, ProperType + TypeVarLikeType, ProperType ) from mypy.nodes import Context def get_target_type( - tvar: TypeVarLikeDef, + tvar: TypeVarLikeType, type: ProperType, callable: CallableType, report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None], diff --git a/mypy/checkmember.py b/mypy/checkmember.py index 64e693d52c96..5a1a91bc17d6 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -5,7 +5,7 @@ from mypy.types import ( Type, Instance, AnyType, TupleType, TypedDictType, CallableType, FunctionLike, - TypeVarLikeDef, Overloaded, TypeVarType, UnionType, PartialType, TypeOfAny, LiteralType, + TypeVarLikeType, Overloaded, TypeVarType, UnionType, PartialType, TypeOfAny, LiteralType, DeletedType, NoneType, TypeType, has_type_vars, get_proper_type, ProperType ) from mypy.nodes import ( @@ -679,7 +679,7 @@ def analyze_class_attribute_access(itype: Instance, name: str, mx: MemberContext, override_info: Optional[TypeInfo] = None, - original_vars: Optional[Sequence[TypeVarLikeDef]] = None + original_vars: Optional[Sequence[TypeVarLikeType]] = None ) -> Optional[Type]: """Analyze access to an attribute on a class object. @@ -842,7 +842,7 @@ def analyze_enum_class_attribute_access(itype: Instance, def add_class_tvars(t: ProperType, isuper: Optional[Instance], is_classmethod: bool, original_type: Type, - original_vars: Optional[Sequence[TypeVarLikeDef]] = None) -> Type: + original_vars: Optional[Sequence[TypeVarLikeType]] = None) -> Type: """Instantiate type variables during analyze_class_attribute_access, e.g T and Q in the following: diff --git a/mypy/messages.py b/mypy/messages.py index 63c77efcd7dc..87c962b6d87b 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -1885,7 +1885,7 @@ def [T <: int] f(self, x: int, y: T) -> None else: tvars.append(tvar.name) else: - # For other TypeVarLikeDefs, just use the repr + # For other TypeVarLikeTypes, just use the repr tvars.append(repr(tvar)) s = '[{}] {}'.format(', '.join(tvars), s) return 'def {}'.format(s) diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py index 992a9782d882..2daeb3f7ca2a 100644 --- a/mypy/tvar_scope.py +++ b/mypy/tvar_scope.py @@ -1,12 +1,12 @@ from typing import Optional, Dict, Union -from mypy.types import TypeVarLikeDef, TypeVarType, ParamSpecDef +from mypy.types import TypeVarLikeType, TypeVarType, ParamSpecDef from mypy.nodes import ParamSpecExpr, TypeVarExpr, TypeVarLikeExpr, SymbolTableNode class TypeVarLikeScope: """Scope that holds bindings for type variables and parameter specifications. - Node fullname -> TypeVarLikeDef. + Node fullname -> TypeVarLikeType. """ def __init__(self, @@ -21,7 +21,7 @@ def __init__(self, prohibited: Type variables that aren't strictly in scope exactly, but can't be bound because they're part of an outer class's scope. """ - self.scope = {} # type: Dict[str, TypeVarLikeDef] + self.scope = {} # type: Dict[str, TypeVarLikeType] self.parent = parent self.func_id = 0 self.class_id = 0 @@ -55,7 +55,7 @@ def class_frame(self) -> 'TypeVarLikeScope': """A new scope frame for binding a class. Prohibits *this* class's tvars""" return TypeVarLikeScope(self.get_function_scope(), True, self) - def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeDef: + def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeType: if self.is_class_scope: self.class_id += 1 i = self.class_id @@ -72,7 +72,7 @@ def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeDef: variance=tvar_expr.variance, line=tvar_expr.line, column=tvar_expr.column - ) # type: TypeVarLikeDef + ) # type: TypeVarLikeType elif isinstance(tvar_expr, ParamSpecExpr): tvar_def = ParamSpecDef( name, @@ -86,10 +86,10 @@ def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeDef: self.scope[tvar_expr.fullname] = tvar_def return tvar_def - def bind_existing(self, tvar_def: TypeVarLikeDef) -> None: + def bind_existing(self, tvar_def: TypeVarLikeType) -> None: self.scope[tvar_def.fullname] = tvar_def - def get_binding(self, item: Union[str, SymbolTableNode]) -> Optional[TypeVarLikeDef]: + def get_binding(self, item: Union[str, SymbolTableNode]) -> Optional[TypeVarLikeType]: fullname = item.fullname if isinstance(item, SymbolTableNode) else item assert fullname is not None if fullname in self.scope: diff --git a/mypy/type_visitor.py b/mypy/type_visitor.py index 8a95ceb049af..27c688a7a235 100644 --- a/mypy/type_visitor.py +++ b/mypy/type_visitor.py @@ -21,7 +21,7 @@ from mypy.types import ( Type, AnyType, CallableType, Overloaded, TupleType, TypedDictType, LiteralType, RawExpressionType, Instance, NoneType, TypeType, - UnionType, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarLikeDef, + UnionType, TypeVarType, PartialType, DeletedType, UninhabitedType, TypeVarLikeType, UnboundType, ErasedType, StarType, EllipsisType, TypeList, CallableArgument, PlaceholderType, TypeAliasType, get_proper_type ) @@ -221,7 +221,7 @@ def translate_types(self, types: Iterable[Type]) -> List[Type]: return [t.accept(self) for t in types] def translate_variables(self, - variables: Sequence[TypeVarLikeDef]) -> Sequence[TypeVarLikeDef]: + variables: Sequence[TypeVarLikeType]) -> Sequence[TypeVarLikeType]: return variables def visit_overloaded(self, t: Overloaded) -> Type: diff --git a/mypy/typeanal.py b/mypy/typeanal.py index bb0adb280bec..dd06408e2694 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -16,7 +16,7 @@ CallableType, NoneType, ErasedType, DeletedType, TypeList, SyntheticTypeVisitor, StarType, PartialType, EllipsisType, UninhabitedType, TypeType, CallableArgument, TypeQuery, union_items, TypeOfAny, LiteralType, RawExpressionType, - PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeDef, ParamSpecDef + PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeType, ParamSpecDef ) from mypy.nodes import ( @@ -917,7 +917,7 @@ def infer_type_variables(self, def bind_function_type_variables( self, fun_type: CallableType, defn: Context - ) -> Sequence[TypeVarLikeDef]: + ) -> Sequence[TypeVarLikeType]: """Find the type variables of the function type and bind them in our tvar_scope""" if fun_type.variables: for var in fun_type.variables: @@ -931,7 +931,7 @@ def bind_function_type_variables( # Do not define a new type variable if already defined in scope. typevars = [(name, tvar) for name, tvar in typevars if not self.is_defined_type_var(name, defn)] - defs = [] # type: List[TypeVarLikeDef] + defs = [] # type: List[TypeVarLikeType] for name, tvar in typevars: if not self.tvar_scope.allow_binding(tvar.fullname): self.fail("Type variable '{}' is bound by an outer class".format(name), defn) @@ -963,7 +963,7 @@ def anal_type(self, t: Type, nested: bool = True) -> Type: if nested: self.nesting_level -= 1 - def anal_var_def(self, var_def: TypeVarLikeDef) -> TypeVarLikeDef: + def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType: if isinstance(var_def, TypeVarType): return TypeVarType( var_def.name, @@ -977,7 +977,7 @@ def anal_var_def(self, var_def: TypeVarLikeDef) -> TypeVarLikeDef: else: return var_def - def anal_var_defs(self, var_defs: Sequence[TypeVarLikeDef]) -> List[TypeVarLikeDef]: + def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> List[TypeVarLikeType]: return [self.anal_var_def(vd) for vd in var_defs] def named_type_with_normalized_str(self, fully_qualified_name: str) -> Instance: diff --git a/mypy/typeops.py b/mypy/typeops.py index 11a902917f70..f6295ccd87f2 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -11,7 +11,7 @@ import sys from mypy.types import ( - TupleType, Instance, FunctionLike, Type, CallableType, TypeVarLikeDef, Overloaded, + TupleType, Instance, FunctionLike, Type, CallableType, TypeVarLikeType, Overloaded, TypeVarType, UninhabitedType, FormalArgument, UnionType, NoneType, TypedDictType, AnyType, TypeOfAny, TypeType, ProperType, LiteralType, get_proper_type, get_proper_types, copy_type, TypeAliasType, TypeQuery @@ -114,7 +114,7 @@ def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance, special_sig: Optional[str], is_new: bool, orig_self_type: Optional[Type] = None) -> CallableType: """Create a type object type based on the signature of __init__.""" - variables = [] # type: List[TypeVarLikeDef] + variables = [] # type: List[TypeVarLikeType] variables.extend(info.defn.type_vars) variables.extend(init_type.variables) @@ -229,7 +229,7 @@ class B(A): pass return cast(F, func) self_param_type = get_proper_type(func.arg_types[0]) - variables = [] # type: Sequence[TypeVarLikeDef] + variables = [] # type: Sequence[TypeVarLikeType] if func.variables and supported_self_type(self_param_type): if original_type is None: # TODO: type check method override (see #7861). @@ -481,7 +481,7 @@ def true_or_false(t: Type) -> ProperType: return new_t -def erase_def_to_union_or_bound(tdef: TypeVarLikeDef) -> Type: +def erase_def_to_union_or_bound(tdef: TypeVarLikeType) -> Type: # TODO(shantanu): fix for ParamSpecDef assert isinstance(tdef, TypeVarType) if tdef.values: diff --git a/mypy/types.py b/mypy/types.py index ea05d0338e86..9b89539bbfb6 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -338,7 +338,7 @@ def is_meta_var(self) -> bool: return self.meta_level > 0 -class TypeVarLikeDef(ProperType): +class TypeVarLikeType(ProperType): name = '' # Name (may be qualified) fullname = '' # Fully qualified name id = None # type: TypeVarId @@ -357,11 +357,11 @@ def serialize(self) -> JsonDict: raise NotImplementedError @classmethod - def deserialize(cls, data: JsonDict) -> 'TypeVarLikeDef': + def deserialize(cls, data: JsonDict) -> 'TypeVarLikeType': raise NotImplementedError -class TypeVarType(TypeVarLikeDef): +class TypeVarType(TypeVarLikeType): """Definition of a single type variable.""" values = None # type: List[Type] # Value restriction, empty list if no restriction upper_bound = None # type: Type @@ -417,7 +417,7 @@ def deserialize(cls, data: JsonDict) -> 'TypeVarType': ) -class ParamSpecDef(TypeVarLikeDef): +class ParamSpecDef(TypeVarLikeType): """Definition of a single ParamSpec variable.""" def __repr__(self) -> str: @@ -975,7 +975,7 @@ def __init__(self, fallback: Instance, name: Optional[str] = None, definition: Optional[SymbolNode] = None, - variables: Optional[Sequence[TypeVarLikeDef]] = None, + variables: Optional[Sequence[TypeVarLikeType]] = None, line: int = -1, column: int = -1, is_ellipsis_args: bool = False, @@ -1029,7 +1029,7 @@ def copy_modified(self, fallback: Bogus[Instance] = _dummy, name: Bogus[Optional[str]] = _dummy, definition: Bogus[SymbolNode] = _dummy, - variables: Bogus[Sequence[TypeVarLikeDef]] = _dummy, + variables: Bogus[Sequence[TypeVarLikeType]] = _dummy, line: Bogus[int] = _dummy, column: Bogus[int] = _dummy, is_ellipsis_args: Bogus[bool] = _dummy, @@ -2085,7 +2085,7 @@ def visit_callable_type(self, t: CallableType) -> str: else: vs.append(var.name) else: - # For other TypeVarLikeDefs, just use the repr + # For other TypeVarLikeTypes, just use the repr vs.append(repr(var)) s = '{} {}'.format('[{}]'.format(', '.join(vs)), s) From fe6865beb4151ab333840ebf9eb47602dfc37a92 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sat, 23 Jan 2021 19:22:10 -0800 Subject: [PATCH 08/11] paramspecdef -> paramspectype --- mypy/applytype.py | 2 +- mypy/checkexpr.py | 2 +- mypy/expandtype.py | 2 +- mypy/tvar_scope.py | 4 ++-- mypy/typeanal.py | 4 ++-- mypy/typeops.py | 2 +- mypy/types.py | 10 +++++----- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/mypy/applytype.py b/mypy/applytype.py index 915352000746..69ba798ebb49 100644 --- a/mypy/applytype.py +++ b/mypy/applytype.py @@ -18,7 +18,7 @@ def get_target_type( context: Context, skip_unsatisfied: bool ) -> Optional[Type]: - # TODO(shantanu): fix for ParamSpecDef + # TODO(shantanu): fix for ParamSpecType assert isinstance(tvar, TypeVarType) values = get_proper_types(tvar.values) if values: diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index ac378313f487..9cf7e22df934 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4449,7 +4449,7 @@ def merge_typevars_in_callables_by_name( for tvdef in target.variables: name = tvdef.fullname if name not in unique_typevars: - # TODO(shantanu): fix for ParamSpecDef + # TODO(shantanu): fix for ParamSpecType assert isinstance(tvdef, TypeVarType) unique_typevars[name] = tvdef variables.append(tvdef) diff --git a/mypy/expandtype.py b/mypy/expandtype.py index 1c512d707299..579cd6cfd473 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -40,7 +40,7 @@ def freshen_function_type_vars(callee: F) -> F: tvdefs = [] tvmap = {} # type: Dict[TypeVarId, Type] for v in callee.variables: - # TODO(shantanu): fix for ParamSpecDef + # TODO(shantanu): fix for ParamSpecType assert isinstance(v, TypeVarType) tvdef = TypeVarType.new_unification_variable(v) tvdefs.append(tvdef) diff --git a/mypy/tvar_scope.py b/mypy/tvar_scope.py index 2daeb3f7ca2a..956dc1ca501c 100644 --- a/mypy/tvar_scope.py +++ b/mypy/tvar_scope.py @@ -1,5 +1,5 @@ from typing import Optional, Dict, Union -from mypy.types import TypeVarLikeType, TypeVarType, ParamSpecDef +from mypy.types import TypeVarLikeType, TypeVarType, ParamSpecType from mypy.nodes import ParamSpecExpr, TypeVarExpr, TypeVarLikeExpr, SymbolTableNode @@ -74,7 +74,7 @@ def bind_new(self, name: str, tvar_expr: TypeVarLikeExpr) -> TypeVarLikeType: column=tvar_expr.column ) # type: TypeVarLikeType elif isinstance(tvar_expr, ParamSpecExpr): - tvar_def = ParamSpecDef( + tvar_def = ParamSpecType( name, tvar_expr.fullname, i, diff --git a/mypy/typeanal.py b/mypy/typeanal.py index dd06408e2694..cce6e6043dd4 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -16,7 +16,7 @@ CallableType, NoneType, ErasedType, DeletedType, TypeList, SyntheticTypeVisitor, StarType, PartialType, EllipsisType, UninhabitedType, TypeType, CallableArgument, TypeQuery, union_items, TypeOfAny, LiteralType, RawExpressionType, - PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeType, ParamSpecDef + PlaceholderType, Overloaded, get_proper_type, TypeAliasType, TypeVarLikeType, ParamSpecType ) from mypy.nodes import ( @@ -683,7 +683,7 @@ def analyze_callable_args_for_paramspec( if sym is None: return None tvar_def = self.tvar_scope.get_binding(sym) - if not isinstance(tvar_def, ParamSpecDef): + if not isinstance(tvar_def, ParamSpecType): return None # TODO(shantanu): construct correct type for paramspec diff --git a/mypy/typeops.py b/mypy/typeops.py index f6295ccd87f2..0a98769fe607 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -482,7 +482,7 @@ def true_or_false(t: Type) -> ProperType: def erase_def_to_union_or_bound(tdef: TypeVarLikeType) -> Type: - # TODO(shantanu): fix for ParamSpecDef + # TODO(shantanu): fix for ParamSpecType assert isinstance(tdef, TypeVarType) if tdef.values: return make_simplified_union(tdef.values) diff --git a/mypy/types.py b/mypy/types.py index 9b89539bbfb6..4bdfee8a03f9 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -417,7 +417,7 @@ def deserialize(cls, data: JsonDict) -> 'TypeVarType': ) -class ParamSpecDef(TypeVarLikeType): +class ParamSpecType(TypeVarLikeType): """Definition of a single ParamSpec variable.""" def __repr__(self) -> str: @@ -426,16 +426,16 @@ def __repr__(self) -> str: def serialize(self) -> JsonDict: assert not self.id.is_meta_var() return { - '.class': 'ParamSpecDef', + '.class': 'ParamSpecType', 'name': self.name, 'fullname': self.fullname, 'id': self.id.raw_id, } @classmethod - def deserialize(cls, data: JsonDict) -> 'ParamSpecDef': - assert data['.class'] == 'ParamSpecDef' - return ParamSpecDef( + def deserialize(cls, data: JsonDict) -> 'ParamSpecType': + assert data['.class'] == 'ParamSpecType' + return ParamSpecType( data['name'], data['fullname'], data['id'], From 4de42d86184b55893831dbe07ae81536f9b5d22d Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sun, 1 Aug 2021 17:51:56 -0700 Subject: [PATCH 09/11] lint --- mypy/types.py | 1 + 1 file changed, 1 insertion(+) diff --git a/mypy/types.py b/mypy/types.py index 82a974dc1ee5..0c000bbc6018 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -915,6 +915,7 @@ def copy_modified(self, *, def has_readable_member(self, name: str) -> bool: return self.type.has_readable_member(name) + class FunctionLike(ProperType): """Abstract base class for function types.""" From ca294b43701022eca7e76f8814771f6de89db16a Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Wed, 4 Aug 2021 00:18:45 -0700 Subject: [PATCH 10/11] more tvdef -> tv --- mypy/checkexpr.py | 30 +++++++++++++++--------------- mypy/expandtype.py | 1 + 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 9e285eb9a229..5aef881aa2ff 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3277,15 +3277,15 @@ def check_lst_expr(self, items: List[Expression], fullname: str, # Used for list and set expressions, as well as for tuples # containing star expressions that don't refer to a # Tuple. (Note: "lst" stands for list-set-tuple. :-) - tvdef = TypeVarType('T', 'T', -1, [], self.object_type()) + tv = TypeVarType('T', 'T', -1, [], self.object_type()) constructor = CallableType( - [tvdef], + [tv], [nodes.ARG_STAR], [None], - self.chk.named_generic_type(fullname, [tvdef]), + self.chk.named_generic_type(fullname, [tv]), self.named_type('builtins.function'), name=tag, - variables=[tvdef]) + variables=[tv]) out = self.check_call(constructor, [(i.expr if isinstance(i, StarExpr) else i) for i in items], @@ -3434,8 +3434,8 @@ def visit_dict_expr(self, e: DictExpr) -> Type: tup.column = value.column args.append(tup) # Define type variables (used in constructors below). - ktdef = TypeVarType('KT', 'KT', -1, [], self.object_type()) - vtdef = TypeVarType('VT', 'VT', -2, [], self.object_type()) + kt = TypeVarType('KT', 'KT', -1, [], self.object_type()) + vt = TypeVarType('VT', 'VT', -2, [], self.object_type()) rv = None # Call dict(*args), unless it's empty and stargs is not. if args or not stargs: @@ -3443,13 +3443,13 @@ def visit_dict_expr(self, e: DictExpr) -> Type: # # def (*v: Tuple[kt, vt]) -> Dict[kt, vt]: ... constructor = CallableType( - [TupleType([ktdef, vtdef], self.named_type('builtins.tuple'))], + [TupleType([kt, vt], self.named_type('builtins.tuple'))], [nodes.ARG_STAR], [None], - self.chk.named_generic_type('builtins.dict', [ktdef, vtdef]), + self.chk.named_generic_type('builtins.dict', [kt, vt]), self.named_type('builtins.function'), name='', - variables=[ktdef, vtdef]) + variables=[kt, vt]) rv = self.check_call(constructor, args, [nodes.ARG_POS] * len(args), e)[0] else: # dict(...) will be called below. @@ -3460,13 +3460,13 @@ def visit_dict_expr(self, e: DictExpr) -> Type: for arg in stargs: if rv is None: constructor = CallableType( - [self.chk.named_generic_type('typing.Mapping', [ktdef, vtdef])], + [self.chk.named_generic_type('typing.Mapping', [kt, vt])], [nodes.ARG_POS], [None], - self.chk.named_generic_type('builtins.dict', [ktdef, vtdef]), + self.chk.named_generic_type('builtins.dict', [kt, vt]), self.named_type('builtins.function'), name='', - variables=[ktdef, vtdef]) + variables=[kt, vt]) rv = self.check_call(constructor, [arg], [nodes.ARG_POS], arg)[0] else: self.check_method_call_by_name('update', rv, [arg], [nodes.ARG_POS], arg) @@ -3756,8 +3756,8 @@ def check_generator_or_comprehension(self, gen: GeneratorExpr, # Infer the type of the list comprehension by using a synthetic generic # callable type. - tvdef = TypeVarType('T', 'T', -1, [], self.object_type()) - tv_list: List[Type] = [tvdef] + tv = TypeVarType('T', 'T', -1, [], self.object_type()) + tv_list: List[Type] = [tv] constructor = CallableType( tv_list, [nodes.ARG_POS], @@ -3765,7 +3765,7 @@ def check_generator_or_comprehension(self, gen: GeneratorExpr, self.chk.named_generic_type(type_name, tv_list + additional_args), self.chk.named_type('builtins.function'), name=id_for_messages, - variables=[tvdef]) + variables=[tv]) return self.check_call(constructor, [gen.left_expr], [nodes.ARG_POS], gen)[0] diff --git a/mypy/expandtype.py b/mypy/expandtype.py index 5bfbfba76aa4..5679d5802782 100644 --- a/mypy/expandtype.py +++ b/mypy/expandtype.py @@ -8,6 +8,7 @@ TypeAliasType, ParamSpecType ) + def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: """Substitute any type variable references in a type given by a type environment. From a1465b9dbd0960e1787475e1adb4d87f05576c9d Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Wed, 4 Aug 2021 00:31:33 -0700 Subject: [PATCH 11/11] comment --- mypy/typeanal.py | 1 + mypy/typevars.py | 1 + 2 files changed, 2 insertions(+) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index 0df5a541f248..07dc704e42ea 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -223,6 +223,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) assert isinstance(tvar_def, TypeVarType) if len(t.args) > 0: self.fail('Type variable "{}" used with arguments'.format(t.name), t) + # Change the line number return TypeVarType( tvar_def.name, tvar_def.fullname, tvar_def.id, tvar_def.values, tvar_def.upper_bound, tvar_def.variance, line=t.line, column=t.column, diff --git a/mypy/typevars.py b/mypy/typevars.py index e6f119be9e6a..f595551bd3bc 100644 --- a/mypy/typevars.py +++ b/mypy/typevars.py @@ -15,6 +15,7 @@ def fill_typevars(typ: TypeInfo) -> Union[Instance, TupleType]: # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars? for i in range(len(typ.defn.type_vars)): tv = typ.defn.type_vars[i] + # Change the line number tv = TypeVarType( tv.name, tv.fullname, tv.id, tv.values, tv.upper_bound, tv.variance, line=-1, column=-1,