[Python-ideas] Make-statement [Re: Different interface for namedtuple?]

Guido van Rossum guido at python.org
Mon Mar 7 17:33:08 CET 2011


On Sun, Mar 6, 2011 at 11:28 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Mon, Mar 7, 2011 at 4:06 PM, Bruce Leban <bruce at leapyear.org> wrote:
>> On Sun, Mar 6, 2011 at 7:11 PM, Guido van Rossum <guido at python.org> wrote:
>>> On Sat, Mar 5, 2011 at 10:27 PM, Carl M. Johnson
>>> <cmjohnson.mailinglist at gmail.com> wrote:> With a little searching, you can
>>> find similar examples of abuse that
>>> > are centered around the with statement rather than metaclasses. People
>>> > have made the with statement into an XML generator
>>> >
>>> > <http://langexplr.blogspot.com/2009/02/writing-xml-with-ironpython-xmlwriter.html>
>>> > or an anonymous block handler
>>> > <http://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython>.
>>>
>>> TBH I find such abuse of 'with' much more troubling.
>>
>> I'm curious if you are troubled by both of these or one more than the other.
>> Personally, the xml writer seems like a reasonable use to me. While I really
>> don't like the anonymous block hack (either the use or the implementation).
>
> The XML example is fine, since it is just another application of
> "before-and-after" coding that the with statement was designed (that
> kind of thing was mentioned explicitly in the PEP 343 discussions,
> although never elaborated to anything like that degree).

I don't think it's fine. The quoted example looks like it depends too
much on implicit side effects.

It is possible that I still (after all these years, and after
enthusiastically supporting its introduction) don't fully appreciate
the with-statement. I find it useful when I can clearly visualize the
alternative code, which typically involves extra flow control such as
a try/finally block. In this example it looks more like the
alternative is just more calls. I expect that in reality the
generation of XML is much more dynamic than in the example, and that
the with-statement won't provide much help (there may even be cases
where it could get in the way).

I was going to say that I don't have much experience with generating
XML, but that's not really true -- I have plenty experience generating
HTML, which is a sufficiently similar experience. In fact I just
hacked together a prototype for an HTML generating library which uses
nested function calls instead of nested with-statements to represent
the nested structure of HTML. I think I like that approach better
because it makes it easier to do some parts of the generation out of
order: I can construct various sub-lists of HTML elements and then
splice them together. E.g.

row1 = []
row2 = []
for x in <something>:
  row1.append(libhtml.td(f1(x)))
  row2.append(libhtml.td(f2(x)))
t = libhtml.table(libhtml.tr(row1), libhtml.tr(row2))

# Etc.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list