Skip to content

Commit a27963b

Browse files
authored
[clean strict optional] Fix another 32 errors (#3265)
* Clean-up treetransform * Clean-up errors(-2), typeanal, maptype
1 parent 8434c8a commit a27963b

File tree

5 files changed

+69
-55
lines changed

5 files changed

+69
-55
lines changed

mypy/errors.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ class ErrorInfo:
2727
module = None # type: Optional[str]
2828

2929
# The name of the type in which this error is located at.
30-
type = '' # Unqualified, may be None
30+
type = '' # type: Optional[str] # Unqualified, may be None
3131

3232
# The name of the function or member in which this error is located at.
33-
function_or_member = '' # Unqualified, may be None
33+
function_or_member = '' # type: Optional[str] # Unqualified, may be None
3434

3535
# The line number related to this error within file.
3636
line = 0 # -1 if unknown
@@ -57,8 +57,8 @@ def __init__(self,
5757
import_ctx: List[Tuple[str, int]],
5858
file: str,
5959
module: Optional[str],
60-
typ: str,
61-
function_or_member: str,
60+
typ: Optional[str],
61+
function_or_member: Optional[str],
6262
line: int,
6363
column: int,
6464
severity: str,
@@ -105,10 +105,10 @@ class Errors:
105105
file = None # type: str
106106

107107
# Stack of short names of currents types (or None).
108-
type_name = None # type: List[str]
108+
type_name = None # type: List[Optional[str]]
109109

110110
# Stack of short names of current functions or members (or None).
111-
function_or_member = None # type: List[str]
111+
function_or_member = None # type: List[Optional[str]]
112112

113113
# Ignore errors on these lines of each file.
114114
ignored_lines = None # type: Dict[str, Set[int]]
@@ -188,7 +188,7 @@ def set_file(self, file: str, module: Optional[str], ignored_lines: Set[int] = N
188188
self.target = [module]
189189

190190
def set_file_ignored_lines(self, file: str,
191-
ignored_lines: Set[int] = None,
191+
ignored_lines: Set[int],
192192
ignore_all: bool = False) -> None:
193193
self.ignored_lines[file] = ignored_lines
194194
if ignore_all:
@@ -265,7 +265,7 @@ def report(self, line: int, column: int, message: str, blocker: bool = False,
265265
only_once: if True, only report this exact message once per build
266266
origin_line: if non-None, override current context as origin
267267
"""
268-
type = self.type_name[-1]
268+
type = self.type_name[-1] # type: Optional[str]
269269
if len(self.function_or_member) > 2:
270270
type = None # Omit type context if nested function
271271
if file is None:
@@ -362,7 +362,7 @@ def targets(self) -> Set[str]:
362362
for info in self.error_info
363363
if info.target)
364364

365-
def render_messages(self, errors: List[ErrorInfo]) -> List[Tuple[str, int, int,
365+
def render_messages(self, errors: List[ErrorInfo]) -> List[Tuple[Optional[str], int, int,
366366
str, str]]:
367367
"""Translate the messages into a sequence of tuples.
368368
@@ -371,12 +371,12 @@ def render_messages(self, errors: List[ErrorInfo]) -> List[Tuple[str, int, int,
371371
item may be None. If the line item is negative, the line
372372
number is not defined for the tuple.
373373
"""
374-
result = [] # type: List[Tuple[str, int, int, str, str]]
374+
result = [] # type: List[Tuple[Optional[str], int, int, str, str]]
375375
# (path, line, column, severity, message)
376376

377377
prev_import_context = [] # type: List[Tuple[str, int]]
378-
prev_function_or_member = None # type: str
379-
prev_type = None # type: str
378+
prev_function_or_member = None # type: Optional[str]
379+
prev_type = None # type: Optional[str]
380380

381381
for e in errors:
382382
# Report module import context, if different from previous message.
@@ -460,10 +460,10 @@ def sort_messages(self, errors: List[ErrorInfo]) -> List[ErrorInfo]:
460460
result.extend(a)
461461
return result
462462

463-
def remove_duplicates(self, errors: List[Tuple[str, int, int, str, str]]
464-
) -> List[Tuple[str, int, int, str, str]]:
463+
def remove_duplicates(self, errors: List[Tuple[Optional[str], int, int, str, str]]
464+
) -> List[Tuple[Optional[str], int, int, str, str]]:
465465
"""Remove duplicates from a sorted error list."""
466-
res = [] # type: List[Tuple[str, int, int, str, str]]
466+
res = [] # type: List[Tuple[Optional[str], int, int, str, str]]
467467
i = 0
468468
while i < len(errors):
469469
dup = False

mypy/maptype.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def map_instance_to_supertypes(instance: Instance,
2828
# FIX: Currently we should only have one supertype per interface, so no
2929
# need to return an array
3030
result = [] # type: List[Instance]
31-
for path in class_derivation_paths(instance.type, supertype):
31+
typ = instance.type
32+
assert typ is not None, 'Instance.type is not fixed after deserialization'
33+
for path in class_derivation_paths(typ, supertype):
3234
types = [instance]
3335
for sup in path:
3436
a = [] # type: List[Instance]
@@ -57,12 +59,14 @@ def class_derivation_paths(typ: TypeInfo,
5759
result = [] # type: List[List[TypeInfo]]
5860

5961
for base in typ.bases:
60-
if base.type == supertype:
61-
result.append([base.type])
62+
btype = base.type
63+
assert btype is not None, 'Instance.type is not fixed after deserialization'
64+
if btype == supertype:
65+
result.append([btype])
6266
else:
6367
# Try constructing a longer path via the base class.
64-
for path in class_derivation_paths(base.type, supertype):
65-
result.append([base.type] + path)
68+
for path in class_derivation_paths(btype, supertype):
69+
result.append([btype] + path)
6670

6771
return result
6872

@@ -71,6 +75,7 @@ def map_instance_to_direct_supertypes(instance: Instance,
7175
supertype: TypeInfo) -> List[Instance]:
7276
# FIX: There should only be one supertypes, always.
7377
typ = instance.type
78+
assert typ is not None, 'Instance.type is not fixed after deserialization'
7479
result = [] # type: List[Instance]
7580

7681
for b in typ.bases:
@@ -98,4 +103,6 @@ def instance_to_type_environment(instance: Instance) -> Dict[TypeVarId, Type]:
98103
arguments. The type variables are mapped by their `id`.
99104
100105
"""
101-
return {binder.id: arg for binder, arg in zip(instance.type.defn.type_vars, instance.args)}
106+
typ = instance.type
107+
assert typ is not None, 'Instance.type is not fixed after deserialization'
108+
return {binder.id: arg for binder, arg in zip(typ.defn.type_vars, instance.args)}

mypy/nodes.py

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -872,9 +872,9 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
872872
class WhileStmt(Statement):
873873
expr = None # type: Expression
874874
body = None # type: Block
875-
else_body = None # type: Block
875+
else_body = None # type: Optional[Block]
876876

877-
def __init__(self, expr: Expression, body: Block, else_body: Block) -> None:
877+
def __init__(self, expr: Expression, body: Block, else_body: Optional[Block]) -> None:
878878
self.expr = expr
879879
self.body = body
880880
self.else_body = else_body
@@ -891,11 +891,11 @@ class ForStmt(Statement):
891891
# Expression to iterate
892892
expr = None # type: Expression
893893
body = None # type: Block
894-
else_body = None # type: Block
894+
else_body = None # type: Optional[Block]
895895
is_async = False # True if `async for ...` (PEP 492, Python 3.5)
896896

897897
def __init__(self, index: Lvalue, expr: Expression, body: Block,
898-
else_body: Block, index_type: 'mypy.types.Type' = None) -> None:
898+
else_body: Optional[Block], index_type: 'mypy.types.Type' = None) -> None:
899899
self.index = index
900900
self.index_type = index_type
901901
self.expr = expr
@@ -956,10 +956,10 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
956956
class IfStmt(Statement):
957957
expr = None # type: List[Expression]
958958
body = None # type: List[Block]
959-
else_body = None # type: Block
959+
else_body = None # type: Optional[Block]
960960

961961
def __init__(self, expr: List[Expression], body: List[Block],
962-
else_body: Block) -> None:
962+
else_body: Optional[Block]) -> None:
963963
self.expr = expr
964964
self.body = body
965965
self.else_body = else_body
@@ -969,10 +969,11 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
969969

970970

971971
class RaiseStmt(Statement):
972-
expr = None # type: Expression
973-
from_expr = None # type: Expression
972+
# Plain 'raise' is a valid statement.
973+
expr = None # type: Optional[Expression]
974+
from_expr = None # type: Optional[Expression]
974975

975-
def __init__(self, expr: Expression, from_expr: Expression = None) -> None:
976+
def __init__(self, expr: Optional[Expression], from_expr: Optional[Expression]) -> None:
976977
self.expr = expr
977978
self.from_expr = from_expr
978979

@@ -982,15 +983,17 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
982983

983984
class TryStmt(Statement):
984985
body = None # type: Block # Try body
985-
types = None # type: List[Expression] # Except type expressions
986-
vars = None # type: List[NameExpr] # Except variable names
986+
# Plain 'except:' also possible
987+
types = None # type: List[Optional[Expression]] # Except type expressions
988+
vars = None # type: List[Optional[NameExpr]] # Except variable names
987989
handlers = None # type: List[Block] # Except bodies
988-
else_body = None # type: Block
989-
finally_body = None # type: Block
990+
else_body = None # type: Optional[Block]
991+
finally_body = None # type: Optional[Block]
990992

991-
def __init__(self, body: Block, vars: List['NameExpr'], types: List[Expression],
992-
handlers: List[Block], else_body: Block,
993-
finally_body: Block) -> None:
993+
def __init__(self, body: Block, vars: List[Optional['NameExpr']],
994+
types: List[Optional[Expression]],
995+
handlers: List[Block], else_body: Optional[Block],
996+
finally_body: Optional[Block]) -> None:
994997
self.body = body
995998
self.vars = vars
996999
self.types = types
@@ -1004,13 +1007,13 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
10041007

10051008
class WithStmt(Statement):
10061009
expr = None # type: List[Expression]
1007-
target = None # type: List[Lvalue]
1010+
target = None # type: List[Optional[Lvalue]]
10081011
# Type given by type comments for target, can be None
10091012
target_type = None # type: mypy.types.Type
10101013
body = None # type: Block
10111014
is_async = False # True if `async with ...` (PEP 492, Python 3.5)
10121015

1013-
def __init__(self, expr: List[Expression], target: List[Lvalue],
1016+
def __init__(self, expr: List[Expression], target: List[Optional[Lvalue]],
10141017
body: Block, target_type: 'mypy.types.Type' = None) -> None:
10151018
self.expr = expr
10161019
self.target = target
@@ -1351,7 +1354,7 @@ class UnaryExpr(Expression):
13511354
op = ''
13521355
expr = None # type: Expression
13531356
# Inferred operator method type
1354-
method_type = None # type: mypy.types.Type
1357+
method_type = None # type: Optional[mypy.types.Type]
13551358

13561359
def __init__(self, op: str, expr: Expression) -> None:
13571360
self.op = op
@@ -1433,7 +1436,7 @@ class OpExpr(Expression):
14331436
left = None # type: Expression
14341437
right = None # type: Expression
14351438
# Inferred type for the operator method type (when relevant).
1436-
method_type = None # type: mypy.types.Type
1439+
method_type = None # type: Optional[mypy.types.Type]
14371440

14381441
def __init__(self, op: str, left: Expression, right: Expression) -> None:
14391442
self.op = op
@@ -1452,7 +1455,7 @@ class ComparisonExpr(Expression):
14521455
operators = None # type: List[str]
14531456
operands = None # type: List[Expression]
14541457
# Inferred type for the operator methods (when relevant; None for 'is').
1455-
method_types = None # type: List[mypy.types.Type]
1458+
method_types = None # type: List[Optional[mypy.types.Type]]
14561459

14571460
def __init__(self, operators: List[str], operands: List[Expression]) -> None:
14581461
self.operators = operators

mypy/treetransform.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Subclass TransformVisitor to perform non-trivial transformations.
44
"""
55

6-
from typing import List, Dict, cast
6+
from typing import List, Dict, cast, Optional, Iterable
77

88
from mypy.nodes import (
99
MypyFile, Import, Node, ImportAll, ImportFrom, FuncItem, FuncDef,
@@ -76,7 +76,7 @@ def visit_import_all(self, node: ImportAll) -> ImportAll:
7676
return ImportAll(node.id, node.relative)
7777

7878
def copy_argument(self, argument: Argument) -> Argument:
79-
init_stmt = None # type: AssignmentStmt
79+
init_stmt = None # type: Optional[AssignmentStmt]
8080

8181
if argument.initialization_statement:
8282
init_lvalue = cast(
@@ -360,7 +360,7 @@ def visit_yield_from_expr(self, node: YieldFromExpr) -> YieldFromExpr:
360360
return YieldFromExpr(self.expr(node.expr))
361361

362362
def visit_yield_expr(self, node: YieldExpr) -> YieldExpr:
363-
return YieldExpr(self.expr(node.expr))
363+
return YieldExpr(self.optional_expr(node.expr))
364364

365365
def visit_await_expr(self, node: AwaitExpr) -> AwaitExpr:
366366
return AwaitExpr(self.expr(node.expr))
@@ -526,7 +526,7 @@ def stmt(self, stmt: Statement) -> Statement:
526526
#
527527
# All the node helpers also propagate line numbers.
528528

529-
def optional_expr(self, expr: Expression) -> Expression:
529+
def optional_expr(self, expr: Optional[Expression]) -> Optional[Expression]:
530530
if expr:
531531
return self.expr(expr)
532532
else:
@@ -537,7 +537,7 @@ def block(self, block: Block) -> Block:
537537
new.line = block.line
538538
return new
539539

540-
def optional_block(self, block: Block) -> Block:
540+
def optional_block(self, block: Optional[Block]) -> Optional[Block]:
541541
if block:
542542
return self.block(block)
543543
else:
@@ -549,7 +549,8 @@ def statements(self, statements: List[Statement]) -> List[Statement]:
549549
def expressions(self, expressions: List[Expression]) -> List[Expression]:
550550
return [self.expr(expr) for expr in expressions]
551551

552-
def optional_expressions(self, expressions: List[Expression]) -> List[Expression]:
552+
def optional_expressions(self, expressions: Iterable[Optional[Expression]]
553+
) -> List[Optional[Expression]]:
553554
return [self.optional_expr(expr) for expr in expressions]
554555

555556
def blocks(self, blocks: List[Block]) -> List[Block]:
@@ -558,8 +559,8 @@ def blocks(self, blocks: List[Block]) -> List[Block]:
558559
def names(self, names: List[NameExpr]) -> List[NameExpr]:
559560
return [self.duplicate_name(name) for name in names]
560561

561-
def optional_names(self, names: List[NameExpr]) -> List[NameExpr]:
562-
result = [] # type: List[NameExpr]
562+
def optional_names(self, names: Iterable[Optional[NameExpr]]) -> List[Optional[NameExpr]]:
563+
result = [] # type: List[Optional[NameExpr]]
563564
for name in names:
564565
if name:
565566
result.append(self.duplicate_name(name))
@@ -571,7 +572,7 @@ def type(self, type: Type) -> Type:
571572
# Override this method to transform types.
572573
return type
573574

574-
def optional_type(self, type: Type) -> Type:
575+
def optional_type(self, type: Optional[Type]) -> Optional[Type]:
575576
if type:
576577
return self.type(type)
577578
else:

mypy/typeanal.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def analyze_type_alias(node: Expression,
4343
lookup_fqn_func: Callable[[str], SymbolTableNode],
4444
tvar_scope: TypeVarScope,
4545
fail_func: Callable[[str, Context], None],
46-
allow_unnormalized: bool = False) -> Type:
46+
allow_unnormalized: bool = False) -> Optional[Type]:
4747
"""Return type if node is valid as a type alias rvalue.
4848
4949
Return None otherwise. 'node' must have been semantically analyzed.
@@ -139,8 +139,8 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
139139
if (fullname in nongen_builtins and t.args and
140140
not sym.normalized and not self.allow_unnormalized):
141141
self.fail(no_subscript_builtin_alias(fullname), t)
142-
if sym.kind == TVAR and self.tvar_scope.get_binding(sym) is not None:
143-
tvar_def = self.tvar_scope.get_binding(sym)
142+
tvar_def = self.tvar_scope.get_binding(sym)
143+
if sym.kind == TVAR and tvar_def is not None:
144144
if len(t.args) > 0:
145145
self.fail('Type variable "{}" used with arguments'.format(
146146
t.name), t)
@@ -196,6 +196,7 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
196196
return UninhabitedType(is_noreturn=True)
197197
elif sym.kind == TYPE_ALIAS:
198198
override = sym.type_override
199+
assert override is not None
199200
an_args = self.anal_array(t.args)
200201
all_vars = self.get_type_var_names(override)
201202
exp_len = len(all_vars)
@@ -453,7 +454,9 @@ def bind_function_type_variables(self,
453454
if not self.tvar_scope.allow_binding(tvar.fullname()):
454455
self.fail("Type variable '{}' is bound by an outer class".format(name), defn)
455456
self.tvar_scope.bind(name, tvar)
456-
defs.append(self.tvar_scope.get_binding(tvar.fullname()))
457+
binding = self.tvar_scope.get_binding(tvar.fullname())
458+
assert binding is not None
459+
defs.append(binding)
457460

458461
return defs
459462

0 commit comments

Comments
 (0)