__init__.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (c) 2015 Marc Brinkmann
  2. # Permission is hereby granted, free of charge, to any person obtaining a
  3. # copy of this software and associated documentation files (the "Software"),
  4. # to deal in the Software without restriction, including without limitation
  5. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  6. # and/or sell copies of the Software, and to permit persons to whom the
  7. # Software is furnished to do so, subject to the following conditions:
  8. # The above copyright notice and this permission notice shall be included in
  9. # all copies or substantial portions of the Software.
  10. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  11. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  13. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  14. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  15. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  16. # DEALINGS IN THE SOFTWARE.
  17. class Visitor(object):
  18. """Base class for visitors."""
  19. def visit(self, node):
  20. """Visit a node.
  21. Calls ``visit_CLASSNAME`` on itself passing ``node``, where
  22. ``CLASSNAME`` is the node's class. If the visitor does not implement an
  23. appropriate visitation method, will go up the
  24. `MRO <https://www.python.org/download/releases/2.3/mro/>`_ until a
  25. match is found.
  26. If the search exhausts all classes of node, raises a
  27. :class:`~exceptions.NotImplementedError`.
  28. :param node: The node to visit.
  29. :return: The return value of the called visitation function.
  30. """
  31. if isinstance(node, type):
  32. mro = node.mro()
  33. else:
  34. mro = type(node).mro()
  35. for cls in mro:
  36. meth = getattr(self, 'visit_' + cls.__name__, None)
  37. if meth is None:
  38. continue
  39. return meth(node)
  40. raise NotImplementedError('No visitation method visit_{}'
  41. .format(node.__class__.__name__))