tags:

views:

70

answers:

6

I like Python's whitespace formatting and legibility. But can you, or is there a common/standard way of delimiting blocks of code that are not to be indented, ie do not belong in nested loops?

I have two parts of a procedure that belong inside a main header. Something like step 2 has parts 2.1 and parts 2.2.

Commenting so far I have something like:

# Section 2
<code>
# Section 2.1
<code>
# Section 2.2
<code>

But I would prefer something like:

# Section 2
<code>
    # Section 2.1
    <code>
    # Section 2.2
    <code>

But neither 2.1 nor 2.2 are sub-loops and I know this is illegal. They just run in sequence but are logical steps (to me) that fall under the 2 header so when I look at my code I know what part of the program they are.

How do you handle these cases when coding?

+6  A: 

Put them in separate functions.

Ignacio Vazquez-Abrams
+5  A: 

What's wrong with function definitions?

def section1( ... ):

def section2( ... ):

def overall( ... ):
    section1()
    section2()

If it's so huge that indentation is required, perhaps it's too huge.

Also, you can abuse the with statement to "force" indentation.

S.Lott
I think you mean "Also, you can abuse the with statement [which does have a purpose, and it's not] to "force" indentation".
jae
You're right about that, @jae.
S.Lott
+2  A: 

You might try splitting this up into multiple functions:

def section2():
    section21()
    section22()

or something similar. I find using functions not only for purposes of reuse but also organizationally makes my code much more readable and easy to maintain. If the functions need to share a significant amount of data, you might consider making them methods of a class.

Noah
+5  A: 

You should not have long functions in Python. Take whitespace dilemmas as a hint.

Hamish Grubijan
s/in Python// ;-)
jae
+2  A: 

I use comments in my code to help me recognize their logical relationship to one-another. If I think that there is some sort of a natural order emerging, I might refactor my code in some way to recognize that, but I never try to mis-use Python's indentation. That's just not what it is meant for. It is syntactical rather than semantic.

Adam Crossland
+2  A: 

I'm surprised you'd consider indenting your code like this even in languages that allow it. How do your team members feel about this? I'd find it very confusing to have indented code that didn't correspond to a block.

Ned Batchelder