Visitor pattern and separating iteration
Mark Lawrence
breamoreboy at yahoo.co.uk
Thu Jul 22 16:35:59 EDT 2010
On 22/07/2010 12:03, Karsten Wutzke wrote:
> Hello,
>
> I'm referring to
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f9ba9816fe4fd55#
>
> I'm currently implementing what looks like a promising solution. I
> have one problem though. My code generator isn't awfully complex, but
> still I have problems trying to figure out where to put the iteration
> code. Ideally, this should be in the classes the generator operates
> on. Take the following Python code from my generator class:
>
> def handleMethod(self, method):
>
> # generate indent depending on object depth in tree
> indent = self.generateIndent(method)
>
> # "public final"
> modifierString = ""
>
> i = 0
>
> for modifier in method.getModifiers():
> if i> 0:
> modifierString += " "
> modifierString += modifier
>
> i += 1
>
> # "String firstName, String lastName"
> parameterString = ""
>
> i = 0
>
> for parameter in method.getParameters():
> if i> 0:
> parameterString += ", "
> parameterString += parameter.getType() + " " +
> parameter.getName()
>
> i += 1
>
> code = indentString + modifierString + " " +
> (method.getReturnType() is None and "" or method.getReturnType() + "
> ") + method.getName() + "(" + parameterString + ")"
>
> code += "\n{"
>
> # here the statements should go
>
> code += "\n}"
>
> return code
>
> The place where the statements should go would require an iteration
> over the statements. When looking at other code samples, you often see
>
> def accept(self, visitor):
> for child in self.getChildren():
> child.accept(visitor)
>
> visitor.visitMyClass(self)
>
> Now, I am wondering how separation of iteration and actual code
> generation can be done in my situation.
>
> def accept(self, generator):
> for child in self.getChildren():
> child.accept(generator)
>
> generator.handleMethod(self)
>
> I could of course add a parameter to handleMethod which would be the
> generated code for the statements, but is that design of any good use
> then? I'm rather tempted to ditch the idea of separating iteration and
> code generation, but then the use of the visitor pattern becomes more
> and more questionable.
>
> What is it I'm missing?
>
> Karsten
I suggest you google for "python patterns alex martelli". From what I've
read, he's forgotten more about Python and/or patterns than most of us
will ever know.
HTH.
Mark Lawrence.
More information about the Python-list
mailing list