Formatting logically nested actions -- Pythonic way?

sturlamolden sturlamolden at yahoo.no
Fri Dec 4 07:31:17 EST 2009


On 4 Des, 07:24, "Alf P. Steinbach" <al... at start.no> wrote:

> And this leads to hierarchical code, which would be nice to indicate by
> indenting, but oops, indenting in Python is syntactically significant...

I've seen this with OpenGL as well. Intendation between glBegin and
glEnd can be achieved with a context manager that calls glBegin in
__enter__ and glEnd in __exit__. Same thing for glColor* and other
functions that set state attributes: call glPushAttrib in __enter__
(before setting new state) and glPopAttrib in __exit__.

Context managers (i.e. with statement) should be used for this, as it
guards against havoc from exceptions. If a context manager is used to
call glPushAttrib and glPopAttrib, a raised exception cannot leave
OpenGL's colour bit and colour stack in an undefined state by skipping
glPopAttrib. The with statement is not just a pritty printer for your
code.

I don't see anything wrong with using context managers for tkinter as
well. But personally I prefer to design GUIs using tools like
wxFormBuilder, GLADE or QtDesigner.












More information about the Python-list mailing list