On python syntax...

Jp Calderone exarkun at intarweb.us
Mon Nov 10 15:03:57 CET 2003


On Mon, Nov 10, 2003 at 05:41:17AM -0800, Steve H wrote:
> [snip]
> 
> 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?


    from StringIO import StringIO
    import types

    def managedIterator(s, i):
        s.write("(")
        for e in i:
            if isinstance(e, types.GeneratorType):
                managedIterator(s, e)
            else:
                s.write(e)
        s.write(")")


    def square():
        def outer():
            for i in range(100):
                yield inner(i)
        def inner(i):
            for j in range(100):
                yield "{%s,%s}" % (i, j)
        return outer()

    s = StringIO()
    managedIterator(s, square())
    print s.getvalue()


  In 2.4, it seems, you will even be able to rewrite square() as:

    def square():
        return (("{%s,%s}" % (i, j) for j in range(100)) for i in range(100))

  Jp





More information about the Python-list mailing list