[Python-ideas] Another indentation style

Steven D'Aprano steve at pearwood.info
Sun Sep 1 11:21:00 CEST 2013


On 01/09/13 18:31, Musical Notation wrote:
> In Haskell, you can write:
>
> let x=1
>      y=2
>
> In Python, why you can't write:
>
> if True: x=x+1
>           y=x
>
> ?

Because allowing that does not let you do anything different or new that you couldn't do before, it would not make code any clearer or more understandable, and it would decrease the readability of the code.

The one-line per block form:

if condition: do_this()

avoids emphasizing the one-line block, and puts the focus on the `if`.  As far as I am concerned, it is not much more than a convenience for the interactive interpreter. Dropping the `if` block onto a second line returns shares focus between the two equally:

if condition:
     do_this()


If Python allowed the form you want with multi-line blocks:

if condition: do_this()
     do_that()
     do_something_else()


the call to `do_this` would be lost, up there in the same line as the test. The block structure looks like this:

..............BLOCK
....BLOCK
....BLOCK


instead of:

.............
....BLOCK
....BLOCK
....BLOCK


and that hurts readability. Worse is the temptation to waste time trying to line everything up:

if condition: do_this()
               do_that()
               do_something_else()
if flag: do_this()
          do_that()
          do_something_else()
if really_long_clause_in_a_boolean_context: do_this()
                                             do_that()
                                             do_something_else()


which obscures the fact that all three `if` blocks are at the same indent level. Even worse:

if condition:                               do_this()
                                             do_that()
                                             do_something_else()
if flag:                                    do_this()
                                             do_that()
                                             do_something_else()
if really_long_clause_in_a_boolean_context: do_this()
                                             do_that()
                                             do_something_else()


which is just abominable. Python doesn't prevent you from writing ugly code, but neither does it allow syntax which encourages you to write ugly code.



-- 
Steven


More information about the Python-ideas mailing list