Small optimizations in dispatch method: 1) lookup node's __class__ once

and store in local; 2) define _preorder to be dispatch (rather than
method that called dispatch).
This commit is contained in:
Jeremy Hylton 2000-10-25 18:02:02 +00:00
parent 821eee3321
commit 66d2c1f7e5
2 changed files with 28 additions and 24 deletions

View file

@ -1,3 +1,4 @@
import sys
from compiler import ast
class ASTVisitor:
@ -40,15 +41,6 @@ class ASTVisitor:
self.node = None
self._cache = {}
def preorder(self, tree, visitor):
"""Do preorder walk of tree using visitor"""
self.visitor = visitor
visitor.visit = self._preorder
self._preorder(tree)
def _preorder(self, node, *args):
return apply(self.dispatch, (node,) + args)
def default(self, node, *args):
for child in node.getChildren():
if isinstance(child, ast.Node):
@ -56,12 +48,14 @@ class ASTVisitor:
def dispatch(self, node, *args):
self.node = node
meth = self._cache.get(node.__class__, None)
className = node.__class__.__name__
klass = node.__class__
meth = self._cache.get(klass, None)
if meth is None:
className = klass.__name__
meth = getattr(self.visitor, 'visit' + className, self.default)
self._cache[node.__class__] = meth
self._cache[klass] = meth
if self.VERBOSE > 0:
className = klass.__name__
if self.VERBOSE == 1:
if meth == 0:
print "dispatch", className
@ -69,6 +63,14 @@ class ASTVisitor:
print "dispatch", className, (meth and meth.__name__ or '')
return apply(meth, (node,) + args)
def preorder(self, tree, visitor):
"""Do preorder walk of tree using visitor"""
self.visitor = visitor
visitor.visit = self._preorder
self._preorder(tree)
_preorder = dispatch
class ExampleASTVisitor(ASTVisitor):
"""Prints examples of the nodes that aren't visited