Structure using whitespace vs logical whitespace

Marek_SP mareksp.92 at gmail.com
Mon Dec 15 18:51:49 CET 2008


On 15 Gru, 18:14, MRAB <goo... at mrabarnett.plus.com> wrote:
> cmdrrickhun... at yaho.com wrote:
> > I've been trying to search through the years of Python talk to find an
> > answer to this, but my Googlefu is weak.
>
> > In most languages, I'll do something like this
>
> > xmlWriter.BeginElement("parent");
> > ----xmlWriter.BeginElement("child");
> > ----------xml.Writer.Characters("subtext");
> > ----xmlWriter.EndElement();
> > xmlWriter.EndElement();
>
> > Where the dashes are indentation (since some newsgroup handlers don't
> > do tabs well).  XML writing is just an example.
>
> > In general, I'm using indentation to show logical flow through code.
> > Python's choice to give semantic meaning to whitespace prevents me
> > from doing such things.  What was once reserved for logical use is now
> > used syntactically.  In 90% of cases, its not needed, and whitespace
> > significance seems to be pretty effective.  In that last 10%, however,
> > I've been frustrated many times.
>
> > I've been using python for a few years, and gotten around this in one
> > way or another, but now I want to get other who work with me to pick
> > up Python.  All newbies to Python have trouble with the idea of
> > whitespace sensitivity, but how can I convince them that "it just
> > works better" when I have this construct which I want to use but
> > can't.
>
> > Has anybody found a way to emulate this behavior?  I've often done it
> > by opening an expression for the whole thing, but there's a lot of
> > tasks where a single expression just isn't sufficient (such as things
> > with assignment).
>
> > PS. In my opinion the solution would be to have the option of entering
> > a "whitespace insensitive" mode which uses C style {} and ;.  The
> > token to enter it could be as complicated as you want (in fact, it may
> > make sense to make it complicated to discourage use unless it's really
> > advantageous).  I'd sugest {{ and }} or something bigger like {={ }
> > =}.  Only two problems: 1) I'm sure it would offend Guido's sense of
> > language aesthetics  2) I'm sure the idea has been hashed over on this
> > newsgroup to death... hence prefering a workaround instead.
>
> You could use the "with" statement:
>
> class xml_element(object):
>      def __init__(self, text):
>          self.text = text
>      def __enter__(self):
>          xmlWriter.BeginElement(self.text)
>      def __exit__(self, *args):
>          xmlWriter.EndElement()
>
> with xml_element("parent"):
>      with xml_element("child"):
>          xmlWriter.Characters("subtext")

Yep, I think that's what Guido was thinking about while adding `with`
statements. They're great at grouping code logically. Before I used
`if True:` to do this but it wasn't good looking.



More information about the Python-list mailing list