Debian Codegraph @

lib-python/3/test/test_type_annotations.py

raw symbols SCIP
1 import textwrap
2 import unittest
3
4 class TypeAnnotationTests(unittest.TestCase):
5
6 def test_lazy_create_annotations(self):
7 # type objects lazy create their __annotations__ dict on demand.
8 # the annotations dict is stored in type.__dict__.
9 # a freshly created type shouldn't have an annotations dict yet.
10 foo = type("Foo", (), {})
11 for i in range(3):
12 self.assertFalse("__annotations__" in foo.__dict__)
13 d = foo.__annotations__
14 self.assertTrue("__annotations__" in foo.__dict__)
15 self.assertEqual(foo.__annotations__, d)
16 self.assertEqual(foo.__dict__['__annotations__'], d)
17 del foo.__annotations__
18
19 def test_setting_annotations(self):
20 foo = type("Foo", (), {})
21 for i in range(3):
22 self.assertFalse("__annotations__" in foo.__dict__)
23 d = {'a': int}
24 foo.__annotations__ = d
25 self.assertTrue("__annotations__" in foo.__dict__)
26 self.assertEqual(foo.__annotations__, d)
27 self.assertEqual(foo.__dict__['__annotations__'], d)
28 del foo.__annotations__
29
30 def test_annotations_getset_raises(self):
31 # builtin types don't have __annotations__ (yet!)
32 with self.assertRaises(AttributeError):
33 print(float.__annotations__)
34 with self.assertRaises(TypeError):
35 float.__annotations__ = {}
36 with self.assertRaises(TypeError):
37 del float.__annotations__
38
39 # double delete
40 foo = type("Foo", (), {})
41 foo.__annotations__ = {}
42 del foo.__annotations__
43 with self.assertRaises(AttributeError):
44 del foo.__annotations__
45
46 def test_annotations_are_created_correctly(self):
47 class C:
48 a:int=3
49 b:str=4
50 self.assertTrue("__annotations__" in C.__dict__)
51 del C.__annotations__
52 self.assertFalse("__annotations__" in C.__dict__)
53
54 def test_descriptor_still_works(self):
55 class C:
56 def __init__(self, name=None, bases=None, d=None):
57 self.my_annotations = None
58
59 @property
60 def __annotations__(self):
61 if not hasattr(self, 'my_annotations'):
62 self.my_annotations = {}
63 if not isinstance(self.my_annotations, dict):
64 self.my_annotations = {}
65 return self.my_annotations
66
67 @__annotations__.setter
68 def __annotations__(self, value):
69 if not isinstance(value, dict):
70 raise ValueError("can only set __annotations__ to a dict")
71 self.my_annotations = value
72
73 @__annotations__.deleter
74 def __annotations__(self):
75 if getattr(self, 'my_annotations', False) is None:
76 raise AttributeError('__annotations__')
77 self.my_annotations = None
78
79 c = C()
80 self.assertEqual(c.__annotations__, {})
81 d = {'a':'int'}
82 c.__annotations__ = d
83 self.assertEqual(c.__annotations__, d)
84 with self.assertRaises(ValueError):
85 c.__annotations__ = 123
86 del c.__annotations__
87 with self.assertRaises(AttributeError):
88 del c.__annotations__
89 self.assertEqual(c.__annotations__, {})
90
91
92 class D(metaclass=C):
93 pass
94
95 self.assertEqual(D.__annotations__, {})
96 d = {'a':'int'}
97 D.__annotations__ = d
98 self.assertEqual(D.__annotations__, d)
99 with self.assertRaises(ValueError):
100 D.__annotations__ = 123
101 del D.__annotations__
102 with self.assertRaises(AttributeError):
103 del D.__annotations__
104 self.assertEqual(D.__annotations__, {})
105
106
107 class TestSetupAnnotations(unittest.TestCase):
108 def check(self, code: str):
109 code = textwrap.dedent(code)
110 for scope in ("module", "class"):
111 with self.subTest(scope=scope):
112 if scope == "class":
113 code = f"class C:\n{textwrap.indent(code, ' ')}"
114 ns = {}
115 exec(code, ns)
116 if scope == "class":
117 annotations = ns["C"].__annotations__
118 else:
119 annotations = ns["__annotations__"]
120 self.assertEqual(annotations, {"x": int})
121
122 def test_top_level(self):
123 self.check("x: int = 1")
124
125 def test_blocks(self):
126 self.check("if True:\n x: int = 1")
127 self.check("""
128 while True:
129 x: int = 1
130 break
131 """)
132 self.check("""
133 while False:
134 pass
135 else:
136 x: int = 1
137 """)
138 self.check("""
139 for i in range(1):
140 x: int = 1
141 """)
142 self.check("""
143 for i in range(1):
144 pass
145 else:
146 x: int = 1
147 """)
148
149 def test_try(self):
150 self.check("""
151 try:
152 x: int = 1
153 except:
154 pass
155 """)
156 self.check("""
157 try:
158 pass
159 except:
160 pass
161 else:
162 x: int = 1
163 """)
164 self.check("""
165 try:
166 pass
167 except:
168 pass
169 finally:
170 x: int = 1
171 """)
172 self.check("""
173 try:
174 1/0
175 except:
176 x: int = 1
177 """)
178
179 def test_try_star(self):
180 self.check("""
181 try:
182 x: int = 1
183 except* Exception:
184 pass
185 """)
186 self.check("""
187 try:
188 pass
189 except* Exception:
190 pass
191 else:
192 x: int = 1
193 """)
194 self.check("""
195 try:
196 pass
197 except* Exception:
198 pass
199 finally:
200 x: int = 1
201 """)
202 self.check("""
203 try:
204 1/0
205 except* Exception:
206 x: int = 1
207 """)
208
209 def test_match(self):
210 self.check("""
211 match 0:
212 case 0:
213 x: int = 1
214 """)