Skip to content

Commit

Permalink
Remove more redundant casts (#1699)
Browse files Browse the repository at this point in the history
  • Loading branch information
rwbarton authored Jun 15, 2016
1 parent 07078e0 commit a3f002f
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 35 deletions.
3 changes: 1 addition & 2 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ def analyze_member_access(name: str, typ: Type, node: Context, is_lvalue: bool,
if method:
if method.is_property:
assert isinstance(method, OverloadedFuncDef)
method = cast(OverloadedFuncDef, method)
return analyze_var(name, method.items[0].var, typ, info, node, is_lvalue, msg,
not_ready_callback)
if is_lvalue:
Expand Down Expand Up @@ -204,7 +203,7 @@ def analyze_var(name: str, var: Var, itype: Instance, info: TypeInfo, node: Cont
# Class-level function objects and classmethods become bound
# methods: the former to the instance, the latter to the
# class.
functype = cast(FunctionLike, t)
functype = t
check_method_type(functype, itype, var.is_classmethod, node, msg)
signature = method_type(functype)
if var.is_property:
Expand Down
2 changes: 1 addition & 1 deletion mypy/checkstrformat.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def check_mapping_str_interpolation(self, specifiers: List[ConversionSpecifier],
replacements: Node) -> None:
dict_with_only_str_literal_keys = (isinstance(replacements, DictExpr) and
all(isinstance(k, (StrExpr, BytesExpr))
for k, v in cast(DictExpr, replacements).items))
for k, v in replacements.items))
if dict_with_only_str_literal_keys:
mapping = {} # type: Dict[str, Type]
for k, v in cast(DictExpr, replacements).items:
Expand Down
2 changes: 1 addition & 1 deletion mypy/expandtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def visit_instance(self, t: Instance) -> Type:
def visit_type_var(self, t: TypeVarType) -> Type:
repl = self.variables.get(t.id, t)
if isinstance(repl, Instance):
inst = cast(Instance, repl)
inst = repl
# Return copy of instance with type erasure flag on.
return Instance(inst.type, inst.args, inst.line, True)
else:
Expand Down
4 changes: 2 additions & 2 deletions mypy/fixup.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def lookup_qualified_stnode(modules: Dict[str, MypyFile], name: str) -> SymbolTa
return stnode
node = stnode.node
assert isinstance(node, TypeInfo)
names = cast(TypeInfo, node).names
names = node.names


def store_qualified(modules: Dict[str, MypyFile], name: str, info: SymbolNode) -> None:
Expand Down Expand Up @@ -278,4 +278,4 @@ def store_qualified(modules: Dict[str, MypyFile], name: str, info: SymbolNode) -
stnode.node = info
return
assert isinstance(node, TypeInfo)
names = cast(TypeInfo, node).names
names = node.names
2 changes: 1 addition & 1 deletion mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2138,7 +2138,7 @@ def deserialize(cls, data: JsonDict) -> 'SymbolTable':
def function_type(func: FuncBase, fallback: 'mypy.types.Instance') -> 'mypy.types.FunctionLike':
if func.type:
assert isinstance(func.type, mypy.types.FunctionLike)
return cast(mypy.types.FunctionLike, func.type)
return func.type
else:
# Implicit type signature with dynamic types.
# Overloaded functions always have a signature, so func must be an ordinary function.
Expand Down
18 changes: 8 additions & 10 deletions mypy/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -867,7 +867,7 @@ def parse_block(self, allow_type: bool = False) -> Tuple[Block, Type]:
if allow_type:
cur = self.current()
if type is None and isinstance(cur, StrLit):
ds = docstring.parse_docstring(cast(StrLit, cur).parsed())
ds = docstring.parse_docstring(cur.parsed())
if ds and False: # TODO: Enable when this is working.
try:
type = parse_str_as_signature(ds.as_type_str(), cur.line)
Expand All @@ -894,15 +894,13 @@ def parse_block(self, allow_type: bool = False) -> Tuple[Block, Type]:

def try_combine_overloads(self, s: Node, stmt: List[Node]) -> bool:
if isinstance(s, Decorator) and stmt:
fdef = cast(Decorator, s)
fdef = s
n = fdef.func.name()
if (isinstance(stmt[-1], Decorator) and
(cast(Decorator, stmt[-1])).func.name() == n):
stmt[-1] = OverloadedFuncDef([cast(Decorator, stmt[-1]), fdef])
if isinstance(stmt[-1], Decorator) and stmt[-1].func.name() == n:
stmt[-1] = OverloadedFuncDef([stmt[-1], fdef])
return True
elif (isinstance(stmt[-1], OverloadedFuncDef) and
(cast(OverloadedFuncDef, stmt[-1])).name() == n):
(cast(OverloadedFuncDef, stmt[-1])).items.append(fdef)
elif isinstance(stmt[-1], OverloadedFuncDef) and stmt[-1].name() == n:
stmt[-1].items.append(fdef)
return True
return False

Expand Down Expand Up @@ -1450,7 +1448,7 @@ def parse_list_expr(self) -> Node:
items[0] = self.parse_generator_expr(items[0])
self.expect(']')
if len(items) == 1 and isinstance(items[0], GeneratorExpr):
return ListComprehension(cast(GeneratorExpr, items[0]))
return ListComprehension(items[0])
else:
expr = ListExpr(items)
return expr
Expand Down Expand Up @@ -1698,7 +1696,7 @@ def parse_member_expr(self, expr: Any) -> Node:
self.expect('.')
name = self.expect_type(Name)
if (isinstance(expr, CallExpr) and isinstance(expr.callee, NameExpr)
and cast(NameExpr, expr.callee).name == 'super'):
and expr.callee.name == 'super'):
# super() expression
node = SuperExpr(name.string) # type: Node
else:
Expand Down
22 changes: 11 additions & 11 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def visit_func_def(self, defn: FuncDef) -> None:
original_def = symbol.node
if self.is_conditional_func(original_def, defn):
# Conditional function definition -- multiple defs are ok.
defn.original_def = cast(FuncDef, original_def)
defn.original_def = original_def
else:
# Report error.
self.check_no_global(defn.name(), defn, True)
Expand Down Expand Up @@ -695,7 +695,7 @@ def clean_up_bases_and_infer_type_variables(self, defn: ClassDef) -> None:
def analyze_typevar_declaration(self, t: Type) -> Optional[List[Tuple[str, TypeVarExpr]]]:
if not isinstance(t, UnboundType):
return None
unbound = cast(UnboundType, t)
unbound = t
sym = self.lookup_qualified(unbound.name, unbound)
if sym is None or sym.node is None:
return None
Expand All @@ -714,7 +714,7 @@ def analyze_typevar_declaration(self, t: Type) -> Optional[List[Tuple[str, TypeV
def analyze_unbound_tvar(self, t: Type) -> Tuple[str, TypeVarExpr]:
if not isinstance(t, UnboundType):
return None
unbound = cast(UnboundType, t)
unbound = t
sym = self.lookup_qualified(unbound.name, unbound)
if sym is not None and sym.kind == UNBOUND_TVAR:
return unbound.name, cast(TypeVarExpr, sym.node)
Expand Down Expand Up @@ -1055,7 +1055,7 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
self.fail)
if res and (not isinstance(res, Instance) or cast(Instance, res).args):
# TODO: What if this gets reassigned?
name = cast(NameExpr, s.lvalues[0])
name = s.lvalues[0]
node = self.lookup(name.name, name)
node.kind = TYPE_ALIAS
node.type_override = res
Expand Down Expand Up @@ -1213,8 +1213,8 @@ def is_self_member_ref(self, memberexpr: MemberExpr) -> bool:
"""Does memberexpr to refer to an attribute of self?"""
if not isinstance(memberexpr.expr, NameExpr):
return False
node = (cast(NameExpr, memberexpr.expr)).node
return isinstance(node, Var) and (cast(Var, node)).is_self
node = memberexpr.expr.node
return isinstance(node, Var) and node.is_self

def check_lvalue_validity(self, node: Node, ctx: Context) -> None:
if isinstance(node, (TypeInfo, TypeVarExpr)):
Expand Down Expand Up @@ -1308,10 +1308,10 @@ def get_typevar_declaration(self, s: AssignmentStmt) -> Optional[CallExpr]:
return None
if not isinstance(s.rvalue, CallExpr):
return None
call = cast(CallExpr, s.rvalue)
call = s.rvalue
if not isinstance(call.callee, RefExpr):
return None
callee = cast(RefExpr, call.callee)
callee = call.callee
if callee.fullname != 'typing.TypeVar':
return None
return call
Expand Down Expand Up @@ -1406,10 +1406,10 @@ def check_namedtuple(self, node: Node, var_name: str = None) -> TypeInfo:
"""
if not isinstance(node, CallExpr):
return None
call = cast(CallExpr, node)
call = node
if not isinstance(call.callee, RefExpr):
return None
callee = cast(RefExpr, call.callee)
callee = call.callee
fullname = callee.fullname
if fullname not in ('collections.namedtuple', 'typing.NamedTuple'):
return None
Expand Down Expand Up @@ -2589,7 +2589,7 @@ def builtin_type(self, name: str, args: List[Type] = None) -> Instance:
names = self.modules['builtins']
sym = names.names[name]
assert isinstance(sym.node, TypeInfo)
return Instance(cast(TypeInfo, sym.node), args or [])
return Instance(sym.node, args or [])


def self_type(typ: TypeInfo) -> Union[Instance, TupleType]:
Expand Down
5 changes: 2 additions & 3 deletions mypy/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ def visit_type_application(self, o: TypeApplication) -> None:
def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
self.line = o.line
if (isinstance(o.rvalue, nodes.CallExpr) and
isinstance(cast(nodes.CallExpr, o.rvalue).analyzed,
nodes.TypeVarExpr)):
isinstance(o.rvalue.analyzed, nodes.TypeVarExpr)):
# Type variable definition -- not a real assignment.
return
if o.type:
Expand Down Expand Up @@ -256,7 +255,7 @@ def visit_callable_type(self, t: CallableType) -> bool:


def is_generic(t: Type) -> bool:
return isinstance(t, Instance) and bool(cast(Instance, t).args)
return isinstance(t, Instance) and bool(t.args)


def is_complex(t: Type) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def is_subtype(left: Type, right: Type,
return True
elif isinstance(right, UnionType) and not isinstance(left, UnionType):
return any(is_subtype(left, item, type_parameter_checker)
for item in cast(UnionType, right).items)
for item in right.items)
else:
return left.accept(SubtypeVisitor(right, type_parameter_checker))

Expand Down
6 changes: 3 additions & 3 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
if len(t.args) == 2 and isinstance(t.args[1], EllipsisType):
# Tuple[T, ...] (uniform, variable-length tuple)
node = self.lookup_fqn_func('builtins.tuple')
info = cast(TypeInfo, node.node)
return Instance(info, [t.args[0].accept(self)], t.line)
tuple_info = cast(TypeInfo, node.node)
return Instance(tuple_info, [t.args[0].accept(self)], t.line)
return self.tuple_type(self.anal_array(t.args))
elif fullname == 'typing.Union':
items = self.anal_array(t.args)
Expand Down Expand Up @@ -152,7 +152,7 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
return AnyType()
self.fail('Invalid type "{}"'.format(name), t)
return t
info = cast(TypeInfo, sym.node)
info = sym.node # type: TypeInfo
if len(t.args) > 0 and info.fullname() == 'builtins.tuple':
return TupleType(self.anal_array(t.args),
Instance(info, [AnyType()], t.line),
Expand Down

0 comments on commit a3f002f

Please sign in to comment.