Monday, May 24, 2010

Small suggestion on Python nested code blocks

I've been coding in Python for a while now, and there's one thing that I've found problematic with regard to nested code blocks. It comes down to the age-old Python debate about whether you like Python's "indentation level" approach to determining what block of code a statement belongs to.

In general I actually like the Python approach. For one thing it removes the debates (going back to at least C) when developing in most languages around what style to use for braces. Especially for people who don't realize that K&R is the way to go.

The problem I have is when I have multiple levels of nesting that ends up being like an overhanging cliff that you can fall off of if you're not careful.

if one_thing:
do_something()
if another thing:
do_another_something()
if third_thing():
do_yet_another_thing()
do_thing_after_cliff()

The two problems I have are that it is harder to keep track of what level of nesting a statement is in for some cases. The bigger problem is if the statement do_thing_after_cliff() accidentally gets modified to be at another indentation level it can be very non-obvious. This can come up when moving chunks of code from one indentation level to another.

I've started using a simple trick to help with this, and for me it really helps visually. Basically I use a double comment "##" where I would normally put the "}" if I was working in another language.

For me this provides the visual cue that helps. And it also should make it obvious enough if statements accidentally get modified to the wrong indentation level.

if one_thing:
do_something()
if another thing:
do_another_something()
if third_thing():
do_yet_another_thing()
##
##
do_thing_after_cliff()
##

I don't use it absolutely everywhere, but it helps in the cases where your eye doesn't immediately feel comfortable with how blocks might line up.

No comments:

Post a Comment