Skip to content

Commit 28718fa

Browse files
authored
Convert MessageBuilder.disable_errors to a context manager (#10569)
1 parent 8853f22 commit 28718fa

25 files changed

+79
-69
lines changed

mypy/backports.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import sys
2+
from contextlib import contextmanager
3+
from typing import Iterator
4+
5+
if sys.version_info < (3, 6):
6+
from collections import OrderedDict as OrderedDict # noqa: F401
7+
else:
8+
# OrderedDict is kind of slow, so for most of our uses in Python 3.6
9+
# and later we'd rather just use dict
10+
OrderedDict = dict
11+
12+
13+
if sys.version_info < (3, 7):
14+
@contextmanager
15+
def nullcontext() -> Iterator[None]:
16+
yield
17+
else:
18+
from contextlib import nullcontext as nullcontext # noqa: F401

mypy/checker.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1995,10 +1995,9 @@ def is_raising_or_empty(self, s: Statement) -> bool:
19951995
if isinstance(s.expr, EllipsisExpr):
19961996
return True
19971997
elif isinstance(s.expr, CallExpr):
1998-
self.expr_checker.msg.disable_errors()
1999-
typ = get_proper_type(self.expr_checker.accept(
2000-
s.expr, allow_none_return=True, always_allow_any=True))
2001-
self.expr_checker.msg.enable_errors()
1998+
with self.expr_checker.msg.disable_errors():
1999+
typ = get_proper_type(self.expr_checker.accept(
2000+
s.expr, allow_none_return=True, always_allow_any=True))
20022001

20032002
if isinstance(typ, UninhabitedType):
20042003
return True
@@ -3050,14 +3049,13 @@ def check_member_assignment(self, instance_type: Type, attribute_type: Type,
30503049
# For non-overloaded setters, the result should be type-checked like a regular assignment.
30513050
# Hence, we first only try to infer the type by using the rvalue as type context.
30523051
type_context = rvalue
3053-
self.msg.disable_errors()
3054-
_, inferred_dunder_set_type = self.expr_checker.check_call(
3055-
dunder_set_type,
3056-
[TempNode(instance_type, context=context), type_context],
3057-
[nodes.ARG_POS, nodes.ARG_POS],
3058-
context, object_type=attribute_type,
3059-
callable_name=callable_name)
3060-
self.msg.enable_errors()
3052+
with self.msg.disable_errors():
3053+
_, inferred_dunder_set_type = self.expr_checker.check_call(
3054+
dunder_set_type,
3055+
[TempNode(instance_type, context=context), type_context],
3056+
[nodes.ARG_POS, nodes.ARG_POS],
3057+
context, object_type=attribute_type,
3058+
callable_name=callable_name)
30613059

30623060
# And now we in fact type check the call, to show errors related to wrong arguments
30633061
# count, etc., replacing the type context for non-overloaded setters only.

mypy/checkexpr.py

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Expression type checker. This file is conceptually part of TypeChecker."""
22

3-
from mypy.ordered_dict import OrderedDict
3+
from mypy.backports import OrderedDict, nullcontext
44
from contextlib import contextmanager
55
import itertools
66
from typing import (
@@ -865,12 +865,11 @@ def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str
865865
res = [] # type: List[Type]
866866
for typ in object_type.relevant_items():
867867
# Member access errors are already reported when visiting the member expression.
868-
self.msg.disable_errors()
869-
item = analyze_member_access(member, typ, e, False, False, False,
870-
self.msg, original_type=object_type, chk=self.chk,
871-
in_literal_context=self.is_literal_context(),
872-
self_type=typ)
873-
self.msg.enable_errors()
868+
with self.msg.disable_errors():
869+
item = analyze_member_access(member, typ, e, False, False, False,
870+
self.msg, original_type=object_type, chk=self.chk,
871+
in_literal_context=self.is_literal_context(),
872+
self_type=typ)
874873
narrowed = self.narrow_type_from_binder(e.callee, item, skip_non_overlapping=True)
875874
if narrowed is None:
876875
continue
@@ -1203,12 +1202,9 @@ def infer_function_type_arguments(self, callee_type: CallableType,
12031202
# due to partial available context information at this time, but
12041203
# these errors can be safely ignored as the arguments will be
12051204
# inferred again later.
1206-
self.msg.disable_errors()
1207-
1208-
arg_types = self.infer_arg_types_in_context(
1209-
callee_type, args, arg_kinds, formal_to_actual)
1210-
1211-
self.msg.enable_errors()
1205+
with self.msg.disable_errors():
1206+
arg_types = self.infer_arg_types_in_context(
1207+
callee_type, args, arg_kinds, formal_to_actual)
12121208

12131209
arg_pass_nums = self.get_arg_infer_passes(
12141210
callee_type.arg_types, formal_to_actual, len(args))
@@ -2798,10 +2794,6 @@ def check_boolean_op(self, e: OpExpr, context: Context) -> Type:
27982794
if left_map is None:
27992795
self.msg.redundant_left_operand(e.op, e.left)
28002796

2801-
# If right_map is None then we know mypy considers the right branch
2802-
# to be unreachable and therefore any errors found in the right branch
2803-
# should be suppressed.
2804-
#
28052797
# Note that we perform these checks *before* we take into account
28062798
# the analysis from the semanal phase below. We assume that nodes
28072799
# marked as unreachable during semantic analysis were done so intentionally.
@@ -2815,13 +2807,11 @@ def check_boolean_op(self, e: OpExpr, context: Context) -> Type:
28152807
elif e.right_always:
28162808
left_map = None
28172809

2818-
if right_map is None:
2819-
self.msg.disable_errors()
2820-
try:
2810+
# If right_map is None then we know mypy considers the right branch
2811+
# to be unreachable and therefore any errors found in the right branch
2812+
# should be suppressed.
2813+
with (self.msg.disable_errors() if right_map is None else nullcontext()):
28212814
right_type = self.analyze_cond_branch(right_map, e.right, left_type)
2822-
finally:
2823-
if right_map is None:
2824-
self.msg.enable_errors()
28252815

28262816
if right_map is None:
28272817
# The boolean expression is statically known to be the left value

mypy/checkmember.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def analyze_type_type_member_access(name: str,
268268
item = None
269269
fallback = mx.builtin_type('builtins.type')
270270
ignore_messages = mx.msg.copy()
271-
ignore_messages.disable_errors()
271+
ignore_messages.disable_errors().__enter__()
272272
if isinstance(typ.item, Instance):
273273
item = typ.item
274274
elif isinstance(typ.item, AnyType):

mypy/errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os.path
22
import sys
33
import traceback
4-
from mypy.ordered_dict import OrderedDict
4+
from mypy.backports import OrderedDict
55
from collections import defaultdict
66

77
from typing import Tuple, List, TypeVar, Set, Dict, Optional, TextIO, Callable

mypy/join.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Calculation of the least upper bound types (joins)."""
22

3-
from mypy.ordered_dict import OrderedDict
3+
from mypy.backports import OrderedDict
44
from typing import List, Optional
55

66
from mypy.types import (

mypy/meet.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from mypy.ordered_dict import OrderedDict
1+
from mypy.backports import OrderedDict
22
from typing import List, Optional, Tuple, Callable
33

44
from mypy.join import (

mypy/messages.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88
Historically we tried to avoid all message string literals in the type
99
checker but we are moving away from this convention.
1010
"""
11+
from contextlib import contextmanager
1112

12-
from mypy.ordered_dict import OrderedDict
13+
from mypy.backports import OrderedDict
1314
import re
1415
import difflib
1516
from textwrap import dedent
1617

17-
from typing import cast, List, Dict, Any, Sequence, Iterable, Tuple, Set, Optional, Union
18+
from typing import cast, List, Dict, Any, Sequence, Iterable, Iterator, Tuple, Set, Optional, Union
1819
from typing_extensions import Final
1920

2021
from mypy.erasetype import erase_type
@@ -136,11 +137,13 @@ def add_errors(self, messages: 'MessageBuilder') -> None:
136137
for info in errs:
137138
self.errors.add_error_info(info)
138139

139-
def disable_errors(self) -> None:
140+
@contextmanager
141+
def disable_errors(self) -> Iterator[None]:
140142
self.disable_count += 1
141-
142-
def enable_errors(self) -> None:
143-
self.disable_count -= 1
143+
try:
144+
yield
145+
finally:
146+
self.disable_count -= 1
144147

145148
def is_errors(self) -> bool:
146149
return self.errors.is_errors()

mypy/nodes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import os
44
from abc import abstractmethod
5-
from mypy.ordered_dict import OrderedDict
5+
from mypy.backports import OrderedDict
66
from collections import defaultdict
77
from typing import (
88
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable, Sequence, Iterator

mypy/nullcontext.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import sys
2+
from contextlib import contextmanager
3+
from typing import Iterator
4+
5+
if sys.version_info < (3, 7):
6+
@contextmanager
7+
def nullcontext() -> Iterator[None]:
8+
yield
9+
else:
10+
from contextlib import nullcontext as nullcontext, contextmanager # noqa: F401

mypy/options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from mypy.ordered_dict import OrderedDict
1+
from mypy.backports import OrderedDict
22
import re
33
import pprint
44
import sys

mypy/ordered_dict.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +0,0 @@
1-
# OrderedDict is kind of slow, so for most of our uses in Python 3.6
2-
# and later we'd rather just use dict
3-
4-
import sys
5-
6-
if sys.version_info < (3, 6):
7-
from collections import OrderedDict as OrderedDict
8-
else:
9-
OrderedDict = dict

mypy/plugins/attrs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Plugin for supporting the attrs library (http://www.attrs.org)"""
22

3-
from mypy.ordered_dict import OrderedDict
3+
from mypy.backports import OrderedDict
44

55
from typing import Optional, Dict, List, cast, Tuple, Iterable
66
from typing_extensions import Final

mypy/semanal_typeddict.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Semantic analysis of TypedDict definitions."""
22

3-
from mypy.ordered_dict import OrderedDict
3+
from mypy.backports import OrderedDict
44
from typing import Optional, List, Set, Tuple
55
from typing_extensions import Final
66

mypy/type_visitor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"""
1313

1414
from abc import abstractmethod
15-
from mypy.ordered_dict import OrderedDict
15+
from mypy.backports import OrderedDict
1616
from typing import Generic, TypeVar, cast, Any, List, Callable, Iterable, Optional, Set, Sequence
1717
from mypy_extensions import trait, mypyc_attr
1818

mypy/typeanal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import itertools
44
from itertools import chain
55
from contextlib import contextmanager
6-
from mypy.ordered_dict import OrderedDict
6+
from mypy.backports import OrderedDict
77

88
from typing import Callable, List, Optional, Set, Tuple, Iterator, TypeVar, Iterable, Sequence
99
from typing_extensions import Final

mypy/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import copy
44
import sys
55
from abc import abstractmethod
6-
from mypy.ordered_dict import OrderedDict
6+
from mypy.backports import OrderedDict
77

88
from typing import (
99
Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple,

mypyc/codegen/emit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Utilities for emitting C code."""
22

3-
from mypy.ordered_dict import OrderedDict
3+
from mypy.backports import OrderedDict
44
from typing import List, Set, Dict, Optional, Callable, Union, Tuple
55
import sys
66

mypyc/codegen/emitclass.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from typing import Optional, List, Tuple, Dict, Callable, Mapping, Set
44

5-
from mypy.ordered_dict import OrderedDict
5+
from mypy.backports import OrderedDict
66

77
from mypyc.common import PREFIX, NATIVE_PREFIX, REG_PREFIX, use_fastcall
88
from mypyc.codegen.emit import Emitter, HeaderDeclaration

mypyc/codegen/emitmodule.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import os
77
import json
8-
from mypy.ordered_dict import OrderedDict
8+
from mypy.backports import OrderedDict
99
from typing import List, Tuple, Dict, Iterable, Set, TypeVar, Optional
1010

1111
from mypy.nodes import MypyFile

mypyc/ir/class_ir.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Intermediate representation of classes."""
22

33
from typing import List, Optional, Set, Tuple, Dict, NamedTuple
4-
from mypy.ordered_dict import OrderedDict
4+
from mypy.backports import OrderedDict
55

66
from mypyc.common import JsonDict
77
from mypyc.ir.ops import Value, DeserMaps

mypyc/irbuild/builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
from typing import Callable, Dict, List, Tuple, Optional, Union, Sequence, Set, Any
1515
from typing_extensions import overload
16-
from mypy.ordered_dict import OrderedDict
16+
from mypy.backports import OrderedDict
1717

1818
from mypy.build import Graph
1919
from mypy.nodes import (

mypyc/irbuild/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def f(x: int) -> int:
2020
below, mypyc.irbuild.builder, and mypyc.irbuild.visitor.
2121
"""
2222

23-
from mypy.ordered_dict import OrderedDict
23+
from mypy.backports import OrderedDict
2424
from typing import List, Dict, Callable, Any, TypeVar, cast
2525

2626
from mypy.nodes import MypyFile, Expression, ClassDef

mypyc/test/test_emitfunc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from typing import List, Optional
44

5-
from mypy.ordered_dict import OrderedDict
5+
from mypy.backports import OrderedDict
66

77
from mypy.test.helpers import assert_string_arrays_equal
88

mypyc/test/test_serialization.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# contain its own tests so that pytest will rewrite the asserts...
55

66
from typing import Any, Dict, Tuple
7-
from mypy.ordered_dict import OrderedDict
7+
from mypy.backports import OrderedDict
88
from collections.abc import Iterable
99

1010
from mypyc.ir.ops import DeserMaps

0 commit comments

Comments
 (0)