On python syntax...

Steve H netspam at shic.co.uk
Mon Nov 10 14:41:17 CET 2003


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?




More information about the Python-list mailing list