Why not allow empty code blocks?

Marko Rauhamaa marko at pacujo.net
Sat Jul 23 07:13:46 EDT 2016


Steven D'Aprano <steve at pearwood.info>:

> On Sat, 23 Jul 2016 01:33 am, Kent Tong wrote:
>> I'm aware that we can use 'pass' as an empty code block. But why
>> doesn't python allow a code block to be empty and thus eliminate the
>> need for this null statement?
>
> Because it cannot tell the difference between an empty code block and
> failing to indent the code block:
>
> for x in sequence:
> print('loop')
>
> Is that meant to print 'loop' each time around the loop, or just once, at
> the end of the loop?

I don't see an ambiguity: obviously the print call takes place after
finishing the loop.

> There are cases where the interpreter could tell:
>
> if flag:
> else:
>    block
>
> Obviously the "if" block is empty. But for consistency, and
> simplicity, the interpreter requires a pass there too.

I wonder if there is any true case of ambiguity. I guess this is all
about an enforced aesthetic principle: GvR doesn't like the looks of an
empty block.

> One less thing to be programmed, one less thing for the user to
> remember. Just require pass any time you have an empty block, rather
> than try to remember where it is required and were it is optional.

Actually, the requirement of a dummy statement is a slight annoyance for
the programmer. After deleting a statement, you must see if you have to
put in a pass statement. And after adding a statement, you may feel the
urge to remove the redundant pass statement.


Marko



More information about the Python-list mailing list