← Back to index
exceptions_context_managers.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 2
FN: 0
Optional: 0 / 0
1
"""
2
Tests
the
handling
of
__exit__
return
types
for
context
managers
.
3
"""
4
5
# Specification: https://typing.readthedocs.io/en/latest/spec/exceptions.html
6
7
8
from
typing
import
Any
,
Literal
,
assert_type
9
10
11
class
CMBase
:
12
def
__enter__
(
self
)
->
None
:
13
pass
14
15
16
class
Suppress1
(
CMBase
):
17
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
bool
:
18
return
True
19
20
21
class
Suppress2
(
CMBase
):
22
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
Literal
[
True
]:
23
return
True
24
25
26
class
NoSuppress1
(
CMBase
):
27
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
None
:
28
return
None
29
30
31
class
NoSuppress2
(
CMBase
):
32
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
Literal
[
False
]:
33
return
False
34
35
36
class
NoSuppress3
(
CMBase
):
37
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
Any
:
38
return
False
39
40
41
class
NoSuppress4
(
CMBase
):
42
def
__exit__
(
self
,
exc_type
,
exc_value
,
traceback
)
->
None
|
bool
:
43
return
None
44
45
46
def
suppress1
(
x
:
int
|
str
)
->
None
:
47
if
isinstance
(
x
,
int
):
48
with
Suppress1
():
49
raise
ValueError
50
assert_type
(
x
,
int
|
str
)
Unexpected error [type-assertion-failure] Type `int | str` does not match asserted type `str`
51
52
53
def
suppress2
(
x
:
int
|
str
)
->
None
:
54
if
isinstance
(
x
,
int
):
55
with
Suppress2
():
56
raise
ValueError
57
assert_type
(
x
,
int
|
str
)
Unexpected error [type-assertion-failure] Type `int | str` does not match asserted type `str`
58
59
60
def
no_suppress1
(
x
:
int
|
str
)
->
None
:
61
if
isinstance
(
x
,
int
):
62
with
NoSuppress1
():
63
raise
ValueError
64
assert_type
(
x
,
str
)
65
66
67
def
no_suppress2
(
x
:
int
|
str
)
->
None
:
68
if
isinstance
(
x
,
int
):
69
with
NoSuppress2
():
70
raise
ValueError
71
assert_type
(
x
,
str
)
72
73
74
def
no_suppress3
(
x
:
int
|
str
)
->
None
:
75
if
isinstance
(
x
,
int
):
76
with
NoSuppress3
():
77
raise
ValueError
78
assert_type
(
x
,
str
)
79
80
81
def
no_suppress4
(
x
:
int
|
str
)
->
None
:
82
if
isinstance
(
x
,
int
):
83
with
NoSuppress4
():
84
raise
ValueError
85
assert_type
(
x
,
str
)