faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 10 people (60%) answered Yes
Recently 2 of 5 people (40%) answered Yes

Entry

Visitor design pattern for Python objects

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 322, Darrell


"""
Packages: miscellaneous
"""
"""
How useful is the visitor pattern in Python ?
Doesn't this solve problems associated with strongly typed languages ?
One useful feature might be had if instead of visitor.visit(self)
you use visitor.myConcreteType(self)
That gives you a switch on type thing so you can avoid this:
    if type(concreteType)==type(xxxx):
        pass
    elif type(......
"""
#!/usr/bin/env python
"""
My twisted view of visitor in Python
Darrell Gallion
"""
class Visitor:
    def __init__(self):
        self._methodDic={}
    def default(self, other):
        print "What's this:", other
    def addMethod(self, method):
        self._methodDic[method.getKey()]=method
    def __call__(self, other):
        method=self._methodDic.get(\
                other.__class__.__name__,self.default)
        return method(other)
class MyVisit:
    """
    Instead of deriving from Visitor the work is
    done by instances with this interface.
    """
    def __init__(self, otherClass):
        self._msg='Visit: %s'%otherClass.__name__
        self._key=otherClass.__name__
    def __call__(self, target):
        print self._msg, target
    def getKey(self):
        return self._key
# Some stuff to visit
class E1:pass
class E2:pass
class E3:pass
collection=[E1(), E1(), E2(), E3()]
visitor=Visitor()
visitor.addMethod(MyVisit(E1))
visitor.addMethod(MyVisit(E2))
map(visitor, collection)
###########################    OUTPUT:
# Visit: E1 <__main__.E1 instance at 7ff6d0>
# Visit: E1 <__main__.E1 instance at 7ff730>
# Visit: E2 <__main__.E2 instance at 7ff780>
# What's this: <__main__.E3 instance at 7ff7b0>