On python syntax...

John Roth newsgroups at jhrothjr.com
Mon Nov 10 09:45:29 EST 2003


"Steve H" <netspam at shic.co.uk> wrote in message
news:eb2f38f3.0311100541.474fa706 at posting.google.com...
> I'm writing a library in which I have a stream object supporting a
> Write mehod, and I require to provide support for writing arbitrary
> strings in arbitrary nested contexts.  A simplified example solution
> might look like this.
>
> --
> # Simplified matching marker calls.
> def Open(s) :
>     s.write("(")
> def Close(s) :
>     s.write(")")
>
> #Main body
> def Square(s) :
>     s.Open()
>     for i in range(100) :
>         s.open
>          for j in range(100) :
>              s.write("{%s,%s}"%i,j)
>          s.close
>     s.close
> --
>
> While this solution would work, I'm less than happy that the
> programmer is left to ensure calls to Open are matched with calls to
> close.  It is significant to note that every call to open is at the
> beginning of a nested context, and every call to close is at the
> corresponing end of the same nested context.
>
> Having glanced through the python manual I notice that the C++ trick
> of using an object with a destructor to manage this sort of behaviour
> is inappropriate for a phython script (as __del__ may be called at any
> time once the ref-count for an object is 0.)  I wonder, is there a
> better approach to this problem than the solution above (maybe using
> lambda functions?)  I'd like a main body of the following form to
> generate the same result:
>
> def Square(s) :
>     ManageContext(s)
>     for i in range(100) :
>         ManageContext(s)
>         for j in range(100) :
>             s.write("{%s,%s}"%i,j)
>
> Any suggestions?

If I wanted things to happen automatically, I'd do one
of two things.

A. Build a stack so that I could insert ending syntax
when I popped something off the stack

B. Use an object oriented approach and build a
tree. Then I could simply tell the tree to write
itself, and each object could handle the ending
syntax.

Also: please don't use tabs for indentation when you're
posting code snippets. There are a number of e-mail and
news readers that simply ignore tabs, causing your
entire program to be neatly left justified, and making
it difficult to read. I've replaced your tabs with spaces
in this reply.

John Roth






More information about the Python-list mailing list