diff --git a/Lib/test/test_type_annotations.py b/Lib/test/test_type_annotations.py index 87f46c2ce8ce61..527acec6acc209 100644 --- a/Lib/test/test_type_annotations.py +++ b/Lib/test/test_type_annotations.py @@ -1,4 +1,5 @@ import unittest +from test.support import run_code class TypeAnnotationTests(unittest.TestCase): @@ -101,3 +102,17 @@ class D(metaclass=C): with self.assertRaises(AttributeError): del D.__annotations__ self.assertEqual(D.__annotations__, {}) + + def test_module_level(self): + ns = run_code("x: int = 1") + self.assertEqual(ns["__annotations__"], {"x": int}) + + ns = run_code("if True:\n x: int = 1") + self.assertEqual(ns["__annotations__"], {"x": int}) + + ns = run_code(""" + match 0: + case 0: + x: int = 1 + """) + self.assertEqual(ns["__annotations__"], {"x": int}) diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-05-31-19-35-22.gh-issue-105164.6Wajph.rst b/Misc/NEWS.d/next/Core and Builtins/2023-05-31-19-35-22.gh-issue-105164.6Wajph.rst new file mode 100644 index 00000000000000..7d3486c3b6e98a --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-05-31-19-35-22.gh-issue-105164.6Wajph.rst @@ -0,0 +1,2 @@ +Ensure annotations are set up correctly if the only annotation in a block is +within a :keyword:`match` block. Patch by Jelle Zijlstra. diff --git a/Python/compile.c b/Python/compile.c index f2314ae11c417b..32eda4d407ea12 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -1422,8 +1422,18 @@ find_ann(asdl_stmt_seq *stmts) find_ann(st->v.TryStar.finalbody) || find_ann(st->v.TryStar.orelse); break; + case Match_kind: + for (j = 0; j < asdl_seq_LEN(st->v.Match.cases); j++) { + match_case_ty match_case = (match_case_ty)asdl_seq_GET( + st->v.Match.cases, j); + if (find_ann(match_case->body)) { + return true; + } + } + break; default: res = false; + break; } if (res) { break;