|
1 | 1 | import textwrap |
| 2 | +import types |
2 | 3 | import unittest |
3 | 4 | from test.support import run_code |
4 | 5 |
|
@@ -212,3 +213,46 @@ def test_match(self): |
212 | 213 | case 0: |
213 | 214 | x: int = 1 |
214 | 215 | """) |
| 216 | + |
| 217 | + |
| 218 | +class AnnotateTests(unittest.TestCase): |
| 219 | + """See PEP 649.""" |
| 220 | + def test_manual_annotate(self): |
| 221 | + def f(): |
| 222 | + pass |
| 223 | + mod = types.ModuleType("mod") |
| 224 | + class X: |
| 225 | + pass |
| 226 | + |
| 227 | + for obj in (f, mod, X): |
| 228 | + with self.subTest(obj=obj): |
| 229 | + self.check_annotations(obj) |
| 230 | + |
| 231 | + def check_annotations(self, f): |
| 232 | + self.assertEqual(f.__annotations__, {}) |
| 233 | + self.assertIs(f.__annotate__, None) |
| 234 | + |
| 235 | + with self.assertRaisesRegex(TypeError, "__annotate__ must be callable or None"): |
| 236 | + f.__annotate__ = 42 |
| 237 | + f.__annotate__ = lambda: 42 |
| 238 | + with self.assertRaisesRegex(TypeError, r"takes 0 positional arguments but 1 was given"): |
| 239 | + print(f.__annotations__) |
| 240 | + |
| 241 | + f.__annotate__ = lambda x: 42 |
| 242 | + with self.assertRaisesRegex(TypeError, r"__annotate__ returned non-dict of type 'int'"): |
| 243 | + print(f.__annotations__) |
| 244 | + |
| 245 | + f.__annotate__ = lambda x: {"x": x} |
| 246 | + self.assertEqual(f.__annotations__, {"x": 1}) |
| 247 | + |
| 248 | + # Setting annotate to None does not invalidate the cached __annotations__ |
| 249 | + f.__annotate__ = None |
| 250 | + self.assertEqual(f.__annotations__, {"x": 1}) |
| 251 | + |
| 252 | + # But setting it to a new callable does |
| 253 | + f.__annotate__ = lambda x: {"y": x} |
| 254 | + self.assertEqual(f.__annotations__, {"y": 1}) |
| 255 | + |
| 256 | + # Setting f.__annotations__ also clears __annotate__ |
| 257 | + f.__annotations__ = {"z": 43} |
| 258 | + self.assertIs(f.__annotate__, None) |
0 commit comments