diff --git a/Doc/library/symtable.rst b/Doc/library/symtable.rst index 95f20b06b5aa1e7..53c65bb1110f2ce 100644 --- a/Doc/library/symtable.rst +++ b/Doc/library/symtable.rst @@ -125,7 +125,10 @@ Examining Symbol Tables .. method:: is_nested() - Return ``True`` if the block is a nested class or function. + Return ``True`` if the block is a function or class nested, directly or + indirectly, within a function. A block defined at module level, or + nested only within classes (and not within any function), is not + considered nested. .. method:: has_children() diff --git a/Lib/symtable.py b/Lib/symtable.py index 9238437191c00f9..99996dd05bcae87 100644 --- a/Lib/symtable.py +++ b/Lib/symtable.py @@ -126,8 +126,12 @@ def is_optimized(self): return bool(self._table.type == _symtable.TYPE_FUNCTION) def is_nested(self): - """Return *True* if the block is a nested class - or function.""" + """Return *True* if the block is a function or class nested, + directly or indirectly, within a function. + + A block defined at module level, or nested only within classes + (and not within any function), is not considered nested. + """ return bool(self._table.nested) def has_children(self): diff --git a/Lib/test/test_symtable.py b/Lib/test/test_symtable.py index 8c03420c4c5e4b1..b941ec3924315b3 100644 --- a/Lib/test/test_symtable.py +++ b/Lib/test/test_symtable.py @@ -234,6 +234,10 @@ def test_optimized(self): def test_nested(self): self.assertFalse(self.top.is_nested()) self.assertFalse(self.Mine.is_nested()) + # gh-99350: a method of a top-level class is not nested, because + # is_nested() reflects being enclosed by a function, not merely + # being nested inside some other block. + self.assertFalse(self.a_method.is_nested()) self.assertFalse(self.spam.is_nested()) self.assertTrue(self.internal.is_nested()) diff --git a/Misc/NEWS.d/next/Documentation/2026-06-22-16-30-00.gh-issue-99350.Wd2rPq.rst b/Misc/NEWS.d/next/Documentation/2026-06-22-16-30-00.gh-issue-99350.Wd2rPq.rst new file mode 100644 index 000000000000000..c7e51473e99e072 --- /dev/null +++ b/Misc/NEWS.d/next/Documentation/2026-06-22-16-30-00.gh-issue-99350.Wd2rPq.rst @@ -0,0 +1,3 @@ +Clarify that :meth:`symtable.SymbolTable.is_nested` returns ``True`` only when +the block is nested (directly or indirectly) within a function, and not when it +is nested merely within another block such as a class.