Why not allow empty code blocks?

BartC bc at freeuk.com
Sat Jul 30 06:15:12 EDT 2016


On 30/07/2016 04:35, Steven D'Aprano wrote:
> On Sat, 30 Jul 2016 06:19 am, BartC wrote:
>
>> The language requires that blocks always contains 1 or more statements.
>> Fair enough, except that 0 statements are often needed
>
> They really aren't.
>
> The standard library uses more "pass" statements than most code I've seen,
> because of the large number of abstract methods and tests that use dummy
> classes or methods. If you are writing library code, or a framework, with
> lots of "do nothing" blocks that the caller is supposed to override, you
> may find yourself doing the same. Even so, the number of "pass" statements
> is a tiny proportion of code, less than one percent for Python 3.6:
>
> [steve at ando Lib]$ wc -l *.py */*.py | tail -n 1
>   541022 total
> [steve at ando Lib]$ grep "pass$" *.py */*.py | wc -l
> 3286
>
>
> Over two thirds of them are from the test suite:
>
> [steve at ando Lib]$ grep "pass$" test/*.py | wc -l
> 2270

Interesting use of 'pass' in this example:

http://pastebin.com/aYJdgEL4

(I do believe he's using 'pass' as 'end'! Although he misses some out in 
that case.)


>
> I feel confident in saying that if you find yourself writing "pass" in
> application code (as opposed to writing a framework or unit tests for a
> library) more than one time in a 500 lines of code, you're doing something
> wrong. But even if it were as high as one time in 100 lines, it is still
> not an onerous requirement.
>
> You should see how many times Ruby programmers have to write "end", 99.9% of
> which are unneeded but forced on them by the language.

Think of it as a pattern. In one language, I used (Algol68-style), a 
simple if was:

   if a then b else c fi

which could also be written more compactly, as suits an expression:

   ( a | b | c )

Then the 'fi' (that is, 'end' or 'end if') is just closing the construct 
started with 'fi', in the same way that ')' closes the opening '('.

As I've mentioned, Python also uses explicit block delimiters in the 
form of else, elif, except, finally (and whichever ones I've misssed):

  if x: a; b elif y: c; d elif z: e; f else: g

In the above syntax, it would be:

  if x then a; b elsif y then c; d elsif z then e; f else g fi

Doesn't it look like there's something missing in the Python? Both the 
'fi' or 'end', and the possibility of an 'h' statement.

Note the Algol68-style style is more free-format where indents are not 
significant.

Anyway, if you're going to talk about annoying things forced upon you by 
the language, what about:

":" after "else"

"()" in "def fn():"

"()" in "print (x)" for Python 3

"for i in range(N):" just to repeat a block N times...

That's apart from the obligatory indents which, with an 'end'-delimited 
scheme, are not always necessary.

-- 
Bartc



More information about the Python-list mailing list