MRAB, 15.07.2010 21:33:
Stefan Behnel wrote:
Karsten Wutzke, 15.07.2010 20:45:
Well, I'm most experienced in OO, so writing OO in Python seems like
the way to start with Python. The visitor pattern uses single-
dispatch, that is, it determines which method to call be the type of
object passed in.

Well, then do that. Put the types into a dict and map them to the
functions to call, then call the function through the dict. That's a
pretty common way to do dispatching.


Note, that I have an hierarchical object structure which I want to
iterate over, so using OO looked natural to me. If there's a better
approach, I'm all ears.

You speak in riddles, but my guess is that your problem is that you
don't want to dispatch mechanism to match only exact types but also
subtypes. No problem, just build your dict incrementally and add new
types as they come in. See this file for an example:

http://hg.cython.org/cython-devel/file/tip/Cython/Compiler/Visitor.py

Another variation: the dispatch table starts with entries for certain
types then it adds subtypes on demand:

def visit(self, obj):
try:
    handler = self.dispatch_table[type(obj)]
except KeyError:
    for disp_type, disp_func in self.dispatch_table.items():
        if isinstance(obj, disp_type):
            self.dispatch_table[type(obj)] = disp_func
            handler = disp_func
        else:
            raise RuntimeError("Visitor does not accept object: %s" % obj)
return handler(obj)

Well, yes, that's basically what the code behind the above link does, except that it follows the type hierarchy correctly to find the closest match.

Stefan

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to