开发者

Python syntax and legibility for sequential steps that are sub-items

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 se开发者_JAVA百科quence 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?


Put them in separate functions.


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


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜