Indentation for code readability

Peter Otten __peter__ at web.de
Fri Mar 30 05:32:58 EDT 2007


DE wrote:

> Hello,
> 
> Here is what I do in C++ and can not right now in python :
> 
> pushMatrix()
> {
>      drawStuff();
> 
>      pushMatrix();
>      {
>             drawSomeOtherStuff()
>      }
>      popMatrix();
> }
> popMatrix();
> 
> The curly brackets have no functional meaning but increase the
> readability significantly. I want to be able to do the same thing in
> python. Since curly brackets are not available and indenting without
> an if or while conditional doesn't work, I have started to question if
> this is possible in python at all.
> 
> Any ideas ?

You could use

if True:
    # do stuff

but I have no sympathy for such self-inflicted noise.

With Python 2.5 you can do even better -- you can emulate what should have
been RAII in your C++ example in the first place:

from __future__ import with_statement

from contextlib import contextmanager

def push_matrix():
    print "push"

def pop_matrix():
    print "pop"

@contextmanager
def matrix():
    m = push_matrix()
    try:
        yield m
    finally:
        pop_matrix()

with matrix():
    print "do stuff"
    with matrix():
        print "do more stuff"

Peter



More information about the Python-list mailing list