[stringtemplate-interest] Python StringTemplate: defining __len__ for class rendered by subtemplate gives empty result
Terence Parr
parrt at cs.usfca.edu
Tue Feb 16 09:58:26 PST 2010
Hi. I'm CC'ing Benjamin, the python guy.
T
On Feb 10, 2010, at 6:59 PM, Wray, Paul wrote:
> Hello
> I've started to use Python StringTemplate (very nice, thank you!), and I
> ran into a surprise that took me a while to track down. Maybe it
> deserves a note in the documentation or perhaps even a rework of part of
> the code? In any case this note may help others.
> The essence of the problem is shown in the code below. Class B defines
> an instance (a) of Class A, and renders it in a (named or anonymous)
> subtemplate, passing (a) either implicitly or explicitly to the
> subtemplate.
>
> The code works fine unless Class A defines a __len__ function for its
> own purposes, which happens to return 0. Then, depending on which form
> of call is used, either the subtemplate is not rendered at all, or the
> attribute reference within the subtemplate gives an empty result.
>
> import stringtemplate3 as st3
> from stringtemplate3.language import DefaultTemplateLexer
> import StringIO
>
> groupStr = '''
> group testGroup;
> Atemplate(it) ::= <<
> $it.value$
>>>
>
> Btemplate(object) ::= <<
> $object.a.value$
> $object.a:{ $it.value$ }$
> $object.a: { itm | $itm.value$ }$
> $object.a:Atemplate()$
> $Atemplate(it=object.a)$
>>>
> '''
>
> class A(object):
> def __init__(self):
> self.value = 'value'
>
> # if subtemplate-rendered class defines __len__, templates are
> empty.
> #def __len__(self):
> # return 0
>
> class B(object):
>
> def __init__(self):
> self.a = A()
>
> def render(self, group):
> template = group.getInstanceOf('Btemplate')
> template['object'] = self
> return template.toString()
>
> if __name__ == '__main__':
> group = st3.StringTemplateGroup(file=StringIO.StringIO(groupStr),
> lexer=DefaultTemplateLexer.Lexer)
> b = B()
> print b.render(group)
> **********************************************************************
> This message is intended for the addressee named and may contain
> privileged information or confidential information or both. If you
> are not the intended recipient please delete it and notify the sender.
> **********************************************************************
> _______________________________________________
> stringtemplate-interest mailing list
> stringtemplate-interest at antlr.org
> http://www.antlr.org/mailman/listinfo/stringtemplate-interest
More information about the stringtemplate-interest
mailing list