Skip to content
This repository was archived by the owner on Apr 23, 2025. It is now read-only.

kira/pyvisitor

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pyvisitor

An implementation of the visitor pattern for Python.

Find more details at Follow-Up to Python Visitor.

Works on both Python 2 and 3. Specifically tested on 2.7.2, 2.7.5, 3.3.2, 3.3.5, and 3.4.0.

usage

First, import the module.

import visitor

Then, define a class that you want to act as the visitor.

class SomeVisitor(object):
  pass

Then, mark the method and parameter that provides dynamic dispatching.

class SomeVisitor(object):
  @visitor.on('node') # Note the name of the parameter in the on decorator
  def visit(self, node);
    pass

Now, override the method on classes that you want called specifically based on the type of the argument.

class SomeVisitor(object):
  @visitor.on('node') # Note the name of the parameter in the on decorator
  def visit(self, node);
    pass

  @visitor.when(MyFirstClass)
  def visit(self, node):
    print 'I am going first class!'

  @visitor.when(MyOtherClass)
  def visit(self, node):
    print 'Whatever. Boring.'

run the example

> git clone [email protected]:realistschuckle/pyvisitor.git
> cd pyvisitor
> python example
Creating the abstract syntax tree that contains x = 5
and printing it
x=5

Creating me and my dependents and printing them
- Curtis
  - Son
  - Daughter
  - Lola a Shitzu

About

An implementation of the visitor pattern for Python.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%