Indentation for code readability

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 30 10:19:06 EDT 2007


"DE" <devrim.erdem at gmail.com> wrote:

> Here is what I do in C++ and can not right now in python :
> 
> pushMatrix()
> {
>      drawStuff();
> 
>      pushMatrix();
>      {
>             drawSomeOtherStuff()
>      }
>      popMatrix();
> }
> popMatrix();
> 

If I understand this contortion is because you have some sort of stack 
and you want the code to follow the depth as you push and pop things 
from the stack.

If you write this in Python then when drawSomeOtherStuff() throws an 
exception your 'stack' will get messed up, so you'll need to add some 
more code to handle this. Using Python 2.5 this is the sort of thing you 
should end up with (and you'll notice that your indentation appears 
naturally when you do this):


from __future__ import with_statement
from contextlib import contextmanager

# Dummy functions so this executes
def pushMatrix(arg): print "pushMatrix", arg
def popMatrix(arg): print "popMatrix", arg
def drawStuff(): print "drawStuff"
def drawSomeOtherStuff(): print "drawSomeOtherStuff"

# The matrix stack implemented as a context handler.
@contextmanager
def NewMatrixContext(arg):
    pushMatrix(arg)
    try:
        yield
    finally:
        popMatrix(arg)

# and finally the function to actually draw stuff in appropriate
# contexts.
def fn():
    with NewMatrixContext(1):
        drawStuff()
        with NewMatrixContext(2):
            drawSomeOtherStuff()

fn()



More information about the Python-list mailing list