From 4db09bb23d28a02700403c61ee7677f8efeaed0f Mon Sep 17 00:00:00 2001 From: Reid Barton Date: Mon, 25 Apr 2016 16:06:58 -0700 Subject: [PATCH] Remove some obsolete casts --- mypy/checker.py | 22 ++++++++++------------ mypy/checkexpr.py | 5 ++--- mypy/checkmember.py | 2 +- mypy/constraints.py | 21 ++++++++------------- mypy/join.py | 15 ++++++--------- mypy/meet.py | 15 ++++++--------- mypy/messages.py | 18 ++++++++---------- mypy/nodes.py | 4 ++-- mypy/sametypes.py | 14 +++++++------- mypy/semanal.py | 20 ++++++++------------ mypy/types.py | 4 ++-- 11 files changed, 60 insertions(+), 80 deletions(-) diff --git a/mypy/checker.py b/mypy/checker.py index 6b5b7234c14c9..ce33850d96a52 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -958,15 +958,14 @@ def check_method_override_for_base_with_name( original_type = base_attr.type if original_type is None and isinstance(base_attr.node, FuncDef): - original_type = self.function_type(cast(FuncDef, - base_attr.node)) + original_type = self.function_type(base_attr.node) if isinstance(original_type, FunctionLike): original = map_type_from_supertype( method_type(original_type), defn.info, base) # Check that the types are compatible. # TODO overloaded signatures - self.check_override(cast(FunctionLike, typ), + self.check_override(typ, cast(FunctionLike, original), defn.name(), name, @@ -1080,16 +1079,16 @@ def check_compatibility(self, name: str, base1: TypeInfo, second = base2[name] first_type = first.type if first_type is None and isinstance(first.node, FuncDef): - first_type = self.function_type(cast(FuncDef, first.node)) + first_type = self.function_type(first.node) second_type = second.type if second_type is None and isinstance(second.node, FuncDef): - second_type = self.function_type(cast(FuncDef, second.node)) + second_type = self.function_type(second.node) # TODO: What if some classes are generic? if (isinstance(first_type, FunctionLike) and isinstance(second_type, FunctionLike)): # Method override - first_sig = method_type(cast(FunctionLike, first_type)) - second_sig = method_type(cast(FunctionLike, second_type)) + first_sig = method_type(first_type) + second_sig = method_type(second_type) ok = is_subtype(first_sig, second_sig) elif first_type and second_type: ok = is_equivalent(first_type, second_type) @@ -1255,7 +1254,7 @@ def check_multi_assignment(self, lvalues: List[Node], lv = lv.expr self.check_assignment(lv, self.temp_node(AnyType(), context), infer_lvalue_type) elif isinstance(rvalue_type, TupleType): - self.check_multi_assignment_from_tuple(lvalues, rvalue, cast(TupleType, rvalue_type), + self.check_multi_assignment_from_tuple(lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type) else: self.check_multi_assignment_from_iterable(lvalues, rvalue_type, @@ -1700,8 +1699,7 @@ def visit_operator_assignment_stmt(self, method, lvalue_type, s.rvalue, s) if isinstance(s.lvalue, IndexExpr): - lv = cast(IndexExpr, s.lvalue) - self.check_indexed_assignment(lv, s.rvalue, s.rvalue) + self.check_indexed_assignment(s.lvalue, s.rvalue, s.rvalue) else: if not is_subtype(rvalue_type, lvalue_type): self.msg.incompatible_operator_assignment(s.op, s) @@ -1742,7 +1740,7 @@ def type_check_raise(self, e: Node, s: RaiseStmt) -> None: # allow `raise type, value, traceback` # https://docs.python.org/2/reference/simple_stmts.html#the-raise-statement # TODO: Also check tuple item types. - if len(cast(TupleType, typ).items) in (2, 3): + if len(typ.items) in (2, 3): return if isinstance(typ, Instance) and typ.type.fallback_to_any: # OK! @@ -1889,7 +1887,7 @@ def analyze_index_variables(self, index: Node, item_type: Type, def visit_del_stmt(self, s: DelStmt) -> Type: if isinstance(s.expr, IndexExpr): - e = cast(IndexExpr, s.expr) # Cast + e = s.expr m = MemberExpr(e.base, '__delitem__') m.line = s.line c = CallExpr(m, [e.index], [nodes.ARG_POS], [None]) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 33f1423e02b03..5a88b4221f00d 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -1102,7 +1102,6 @@ def visit_index_expr_helper(self, e: IndexExpr) -> Type: return self.accept(e.analyzed) left_type = self.accept(e.base) if isinstance(left_type, TupleType) and self.chk.typing_mode_full(): - left_type = cast(TupleType, left_type) # Special case for tuples. They support indexing only by integer # literals. (Except in weak type checking mode.) index = e.index @@ -1210,7 +1209,7 @@ def visit_tuple_expr(self, e: TupleExpr) -> Type: ctx = None # type: TupleType # Try to determine type context for type inference. if isinstance(self.chk.type_context[-1], TupleType): - t = cast(TupleType, self.chk.type_context[-1]) + t = self.chk.type_context[-1] if len(t.items) == len(e.items): ctx = t # Infer item types. @@ -1582,7 +1581,7 @@ def map_actuals_to_formals(caller_kinds: List[int], def is_empty_tuple(t: Type) -> bool: - return isinstance(t, TupleType) and not cast(TupleType, t).items + return isinstance(t, TupleType) and not t.items def is_duplicate_mapping(mapping: List[int], actual_kinds: List[int]) -> bool: diff --git a/mypy/checkmember.py b/mypy/checkmember.py index 152728ea64269..8eeea0260a1a0 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -288,7 +288,7 @@ def analyze_class_attribute_access(itype: Instance, return AnyType() if isinstance(node.node, TypeInfo): - return type_object_type(cast(TypeInfo, node.node), builtin_type) + return type_object_type(node.node, builtin_type) if is_decorated: # TODO: Return type of decorated function. This is quick hack to work around #998. diff --git a/mypy/constraints.py b/mypy/constraints.py index b80a7fc804436..699c320daaa06 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -81,16 +81,14 @@ def get_actual_type(arg_type: Type, kind: int, return AnyType() elif isinstance(arg_type, TupleType): # Get the next tuple item of a tuple *arg. - tuplet = cast(TupleType, arg_type) tuple_counter[0] += 1 - return tuplet.items[tuple_counter[0] - 1] + return arg_type.items[tuple_counter[0] - 1] else: return AnyType() elif kind == nodes.ARG_STAR2: - if isinstance(arg_type, Instance) and ( - (cast(Instance, arg_type)).type.fullname() == 'builtins.dict'): + if isinstance(arg_type, Instance) and (arg_type.type.fullname() == 'builtins.dict'): # Dict **arg. TODO more general (Mapping) - return (cast(Instance, arg_type)).args[1] + return arg_type.args[1] else: return AnyType() else: @@ -176,7 +174,7 @@ def visit_instance(self, template: Instance) -> List[Constraint]: actual = self.actual res = [] # type: List[Constraint] if isinstance(actual, Instance): - instance = cast(Instance, actual) + instance = actual if (self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname())): mapped = map_instance_to_supertype(template, instance.type) @@ -208,7 +206,6 @@ def visit_instance(self, template: Instance) -> List[Constraint]: is_named_instance(template, 'typing.Sequence') or is_named_instance(template, 'typing.Reversible')) and self.direction == SUPERTYPE_OF): - actual = cast(TupleType, actual) for item in actual.items: cb = infer_constraints(template.args[0], item, SUPERTYPE_OF) res.extend(cb) @@ -218,7 +215,7 @@ def visit_instance(self, template: Instance) -> List[Constraint]: def visit_callable_type(self, template: CallableType) -> List[Constraint]: if isinstance(self.actual, CallableType): - cactual = cast(CallableType, self.actual) + cactual = self.actual # FIX verify argument counts # FIX what if one of the functions is generic res = [] # type: List[Constraint] @@ -240,8 +237,7 @@ def visit_callable_type(self, template: CallableType) -> List[Constraint]: self.direction)) return res elif isinstance(self.actual, Overloaded): - return self.infer_against_overloaded(cast(Overloaded, self.actual), - template) + return self.infer_against_overloaded(self.actual, template) else: return [] @@ -258,12 +254,11 @@ def infer_against_overloaded(self, overloaded: Overloaded, def visit_tuple_type(self, template: TupleType) -> List[Constraint]: actual = self.actual - if (isinstance(actual, TupleType) and - len((cast(TupleType, actual)).items) == len(template.items)): + if isinstance(actual, TupleType) and len(actual.items) == len(template.items): res = [] # type: List[Constraint] for i in range(len(template.items)): res.extend(infer_constraints(template.items[i], - cast(TupleType, actual).items[i], + actual.items[i], self.direction)) return res elif isinstance(actual, AnyType): diff --git a/mypy/join.py b/mypy/join.py index 3adb9531e5a2e..2ae03602120bd 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -120,14 +120,14 @@ def visit_erased_type(self, t: ErasedType) -> Type: return self.s def visit_type_var(self, t: TypeVarType) -> Type: - if isinstance(self.s, TypeVarType) and (cast(TypeVarType, self.s)).id == t.id: + if isinstance(self.s, TypeVarType) and self.s.id == t.id: return self.s else: return self.default(self.s) def visit_instance(self, t: Instance) -> Type: if isinstance(self.s, Instance): - return join_instances(t, cast(Instance, self.s)) + return join_instances(t, self.s) elif isinstance(self.s, FunctionLike): return join_types(t, self.s.fallback) else: @@ -135,9 +135,8 @@ def visit_instance(self, t: Instance) -> Type: def visit_callable_type(self, t: CallableType) -> Type: # TODO: Consider subtyping instead of just similarity. - if isinstance(self.s, CallableType) and is_similar_callables( - t, cast(CallableType, self.s)): - return combine_similar_callables(t, cast(CallableType, self.s)) + if isinstance(self.s, CallableType) and is_similar_callables(t, self.s): + return combine_similar_callables(t, self.s) elif isinstance(self.s, Overloaded): # Switch the order of arguments to that we'll get to visit_overloaded. return join_types(t, self.s) @@ -191,12 +190,10 @@ def visit_overloaded(self, t: Overloaded) -> Type: return join_types(t.fallback, s) def visit_tuple_type(self, t: TupleType) -> Type: - if (isinstance(self.s, TupleType) and - cast(TupleType, self.s).length() == t.length()): + if isinstance(self.s, TupleType) and self.s.length() == t.length(): items = [] # type: List[Type] for i in range(t.length()): - items.append(self.join(t.items[i], - (cast(TupleType, self.s)).items[i])) + items.append(self.join(t.items[i], self.s.items[i])) # TODO: What if the fallback types are different? return TupleType(items, t.fallback) else: diff --git a/mypy/meet.py b/mypy/meet.py index 6c09487659ebc..88b4d4f6ac36b 100644 --- a/mypy/meet.py +++ b/mypy/meet.py @@ -158,14 +158,14 @@ def visit_erased_type(self, t: ErasedType) -> Type: return self.s def visit_type_var(self, t: TypeVarType) -> Type: - if isinstance(self.s, TypeVarType) and (cast(TypeVarType, self.s)).id == t.id: + if isinstance(self.s, TypeVarType) and self.s.id == t.id: return self.s else: return self.default(self.s) def visit_instance(self, t: Instance) -> Type: if isinstance(self.s, Instance): - si = cast(Instance, self.s) + si = self.s if t.type == si.type: if is_subtype(t, self.s) or is_subtype(self.s, t): # Combine type arguments. We could have used join below @@ -188,19 +188,16 @@ def visit_instance(self, t: Instance) -> Type: return self.default(self.s) def visit_callable_type(self, t: CallableType) -> Type: - if isinstance(self.s, CallableType) and is_similar_callables( - t, cast(CallableType, self.s)): - return combine_similar_callables(t, cast(CallableType, self.s)) + if isinstance(self.s, CallableType) and is_similar_callables(t, self.s): + return combine_similar_callables(t, self.s) else: return self.default(self.s) def visit_tuple_type(self, t: TupleType) -> Type: - if isinstance(self.s, TupleType) and ( - cast(TupleType, self.s).length() == t.length()): + if isinstance(self.s, TupleType) and self.s.length() == t.length(): items = [] # type: List[Type] for i in range(t.length()): - items.append(self.meet(t.items[i], - (cast(TupleType, self.s)).items[i])) + items.append(self.meet(t.items[i], self.s.items[i])) # TODO: What if the fallbacks are different? return TupleType(items, t.fallback) else: diff --git a/mypy/messages.py b/mypy/messages.py index 151c9ecdd38c4..9d548498e5213 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -160,7 +160,7 @@ def format(self, typ: Type, verbosity: int = 0) -> str: # If format_simple returns a non-trivial result, use that. return s elif isinstance(typ, FunctionLike): - func = cast(FunctionLike, typ) + func = typ if func.is_type_obj(): # The type of a type object type can be derived from the # return type (this always works). @@ -199,7 +199,7 @@ def format_simple(self, typ: Type, verbosity: int = 0) -> str: callable type -> "" (empty string) """ if isinstance(typ, Instance): - itype = cast(Instance, typ) + itype = typ # Get the short name of the type. if verbosity >= 2: base_str = itype.type.fullname() @@ -233,13 +233,13 @@ def format_simple(self, typ: Type, verbosity: int = 0) -> str: return '{}[...]'.format(base_str) elif isinstance(typ, TypeVarType): # This is similar to non-generic instance types. - return '"{}"'.format((cast(TypeVarType, typ)).name) + return '"{}"'.format(typ.name) elif isinstance(typ, TupleType): # Prefer the name of the fallback class (if not tuple), as it's more informative. if typ.fallback.type.fullname() != 'builtins.tuple': return self.format_simple(typ.fallback) items = [] - for t in (cast(TupleType, typ)).items: + for t in typ.items: items.append(strip_quotes(self.format(t))) s = '"Tuple[{}]"'.format(', '.join(items)) if len(s) < 40: @@ -248,7 +248,7 @@ def format_simple(self, typ: Type, verbosity: int = 0) -> str: return 'tuple(length {})'.format(len(items)) elif isinstance(typ, UnionType): items = [] - for t in (cast(UnionType, typ)).items: + for t in typ.items: items.append(strip_quotes(self.format(t))) s = '"Union[{}]"'.format(', '.join(items)) if len(s) < 40: @@ -300,7 +300,7 @@ def has_no_attr(self, typ: Type, member: str, context: Context) -> Type: messages. Return type Any. """ if (isinstance(typ, Instance) and - (cast(Instance, typ)).type.has_readable_member(member)): + typ.type.has_readable_member(member)): self.fail('Member "{}" is not assignable'.format(member), context) elif isinstance(typ, Void): self.check_void(typ, context) @@ -336,8 +336,7 @@ def has_no_attr(self, typ: Type, member: str, context: Context) -> Type: # The non-special case: a missing ordinary attribute. if not self.disable_type_names: failed = False - if isinstance(typ, Instance) and cast(Instance, typ).type.names: - typ = cast(Instance, typ) + if isinstance(typ, Instance) and typ.type.names: alternatives = set(typ.type.names.keys()) matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] matches.extend(best_matches(member, alternatives)[:3]) @@ -681,8 +680,7 @@ def invalid_var_arg(self, typ: Type, context: Context) -> None: self.fail('List or tuple expected as variable arguments', context) def invalid_keyword_var_arg(self, typ: Type, context: Context) -> None: - if isinstance(typ, Instance) and ( - (cast(Instance, typ)).type.fullname() == 'builtins.dict'): + if isinstance(typ, Instance) and (typ.type.fullname() == 'builtins.dict'): self.fail('Keywords must be strings', context) else: self.fail('Argument after ** must be a dictionary', diff --git a/mypy/nodes.py b/mypy/nodes.py index 34516cccba2b7..89ddb76e54697 100644 --- a/mypy/nodes.py +++ b/mypy/nodes.py @@ -1815,7 +1815,7 @@ def get_var(self, name: str) -> Var: if name in cls.names: node = cls.names[name].node if isinstance(node, Var): - return cast(Var, node) + return node else: return None return None @@ -1988,7 +1988,7 @@ def type(self) -> 'mypy.types.Type': and node.type is not None): return node.type elif isinstance(node, Decorator): - return (cast(Decorator, node)).var.type + return node.var.type else: return None diff --git a/mypy/sametypes.py b/mypy/sametypes.py index 9b0013247829b..bfe37a6a1394b 100644 --- a/mypy/sametypes.py +++ b/mypy/sametypes.py @@ -1,4 +1,4 @@ -from typing import cast, Sequence +from typing import Sequence from mypy.types import ( Type, UnboundType, ErrorType, AnyType, NoneTyp, Void, TupleType, UnionType, CallableType, @@ -78,17 +78,17 @@ def visit_deleted_type(self, left: DeletedType) -> bool: def visit_instance(self, left: Instance) -> bool: return (isinstance(self.right, Instance) and - left.type == (cast(Instance, self.right)).type and - is_same_types(left.args, (cast(Instance, self.right)).args)) + left.type == self.right.type and + is_same_types(left.args, self.right.args)) def visit_type_var(self, left: TypeVarType) -> bool: return (isinstance(self.right, TypeVarType) and - left.id == (cast(TypeVarType, self.right)).id) + left.id == self.right.id) def visit_callable_type(self, left: CallableType) -> bool: # FIX generics if isinstance(self.right, CallableType): - cright = cast(CallableType, self.right) + cright = self.right return (is_same_type(left.ret_type, cright.ret_type) and is_same_types(left.arg_types, cright.arg_types) and left.arg_names == cright.arg_names and @@ -100,14 +100,14 @@ def visit_callable_type(self, left: CallableType) -> bool: def visit_tuple_type(self, left: TupleType) -> bool: if isinstance(self.right, TupleType): - return is_same_types(left.items, cast(TupleType, self.right).items) + return is_same_types(left.items, self.right.items) else: return False def visit_union_type(self, left: UnionType) -> bool: # XXX This is a test for syntactic equality, not equivalence if isinstance(self.right, UnionType): - return is_same_types(left.items, cast(UnionType, self.right).items) + return is_same_types(left.items, self.right.items) else: return False diff --git a/mypy/semanal.py b/mypy/semanal.py index 2655ea2fe27e5..fd05b0cb246b3 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -1108,8 +1108,7 @@ def analyze_lvalue(self, lval: Node, nested: bool = False, elif isinstance(lval.node, Var) and lval.is_def: # Since the is_def flag is set, this must have been analyzed # already in the first pass and added to the symbol table. - v = cast(Var, lval.node) - assert v.name() in self.globals + assert lval.node.name() in self.globals elif (self.is_func_scope() and lval.name not in self.locals[-1] and lval.name not in self.global_decls[-1] and lval.name not in self.nonlocal_decls[-1]): @@ -1213,7 +1212,7 @@ def store_declared_types(self, lvalue: Node, typ: Type) -> None: if isinstance(lvalue, RefExpr): lvalue.is_def = False if isinstance(lvalue.node, Var): - var = cast(Var, lvalue.node) + var = lvalue.node var.type = typ var.is_ready = True # If node is not a variable, we'll catch it elsewhere. @@ -1438,7 +1437,7 @@ def parse_namedtuple_args(self, call: CallExpr, return self.fail_namedtuple_arg( "List literal expected as the second argument to namedtuple()", call) else: - listexpr = cast(ListExpr, args[1]) + listexpr = args[1] if fullname == 'collections.namedtuple': # The fields argument contains just names, with implicit Any types. if any(not isinstance(item, (StrExpr, BytesExpr)) for item in listexpr.items): @@ -1864,9 +1863,8 @@ def visit_member_expr(self, expr: MemberExpr) -> None: base = expr.expr base.accept(self) # Bind references to module attributes. - if isinstance(base, RefExpr) and cast(RefExpr, - base).kind == MODULE_REF: - file = cast(MypyFile, cast(RefExpr, base).node) + if isinstance(base, RefExpr) and base.kind == MODULE_REF: + file = cast(MypyFile, base.node) n = file.names.get(expr.name, None) if file is not None else None if n: n = self.normalize_type_alias(n, expr) @@ -1906,7 +1904,7 @@ def visit_index_expr(self, expr: IndexExpr) -> None: # Translate index to an unanalyzed type. types = [] # type: List[Type] if isinstance(expr.index, TupleExpr): - items = (cast(TupleExpr, expr.index)).items + items = expr.index.items else: items = [expr.index] for item in items: @@ -2577,15 +2575,13 @@ def set_callable_name(sig: Type, fdef: FuncDef) -> Type: def refers_to_fullname(node: Node, fullname: str) -> bool: """Is node a name or member expression with the given full name?""" - return isinstance(node, - RefExpr) and cast(RefExpr, node).fullname == fullname + return isinstance(node, RefExpr) and node.fullname == fullname def refers_to_class_or_function(node: Node) -> bool: """Does semantically analyzed node refer to a class?""" return (isinstance(node, RefExpr) and - isinstance(cast(RefExpr, node).node, (TypeInfo, FuncDef, - OverloadedFuncDef))) + isinstance(node.node, (TypeInfo, FuncDef, OverloadedFuncDef))) def calculate_class_mro(defn: ClassDef, fail: Callable[[str, Context], None]) -> None: diff --git a/mypy/types.py b/mypy/types.py index 24a77f5f48e99..1d2c231abc6e8 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -721,8 +721,8 @@ def has_readable_member(self, name: str) -> bool: TODO: Deal with attributes of TupleType etc. TODO: This should probably be refactored to go elsewhere. """ - return all((isinstance(x, UnionType) and cast(UnionType, x).has_readable_member(name)) or - (isinstance(x, Instance) and cast(Instance, x).type.has_readable_member(name)) + return all((isinstance(x, UnionType) and x.has_readable_member(name)) or + (isinstance(x, Instance) and x.type.has_readable_member(name)) for x in self.items) def serialize(self) -> JsonDict: