From ab2537e12dc0b3d5b92feb881d0f5d6e9086e4e4 Mon Sep 17 00:00:00 2001 From: Syed Ahmed Hussain Date: Fri, 20 Dec 2024 23:51:30 +0530 Subject: [PATCH] ast.NodeVisitor: add feat to return all 'visit_...' calls' combined returns --- Lib/ast.py | 16 ++++++++++++++-- ...024-12-20-20-57-43.gh-issue-128127.qqkW3b.rst | 4 ++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2024-12-20-20-57-43.gh-issue-128127.qqkW3b.rst diff --git a/Lib/ast.py b/Lib/ast.py index 154d2c8c1f9ebb..9775a52ce5f057 100644 --- a/Lib/ast.py +++ b/Lib/ast.py @@ -501,18 +501,26 @@ class NodeVisitor(object): class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node - (return value `None`) the `generic_visit` visitor is used instead. + (return value `list` | `None`) the `generic_visit` visitor is used instead. + The `generic_visit` visitor iterates the nodes, calls appropriate `visit_` method + and returns a list of all return values of ``'visit_'`` method calls. Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications. """ + def __init__(self): + self.visited_items = [] def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) - return visitor(node) + visited = visitor(node) + if (visitor != self.generic_visit) and not isinstance(visited, list): + if hasattr(self, 'visited_items'): + self.visited_items.append(visited) + return visited def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" @@ -523,6 +531,10 @@ def generic_visit(self, node): self.visit(item) elif isinstance(value, AST): self.visit(value) + try: + return self.visited_items + except AttributeError: + return None class NodeTransformer(NodeVisitor): diff --git a/Misc/NEWS.d/next/Library/2024-12-20-20-57-43.gh-issue-128127.qqkW3b.rst b/Misc/NEWS.d/next/Library/2024-12-20-20-57-43.gh-issue-128127.qqkW3b.rst new file mode 100644 index 00000000000000..870bea5287eb6d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-12-20-20-57-43.gh-issue-128127.qqkW3b.rst @@ -0,0 +1,4 @@ +Change behaviour of NodeVisitor's generic_visit to return list of return +values of calls to visit_x method instead of None. For new functionailty to +work derived classes need to call NodeVisitors constructor otherwise, it +behaves same as before(returns None).