[Python-ideas] Reducing colon uses to increase readability

Andre Roberge andre.roberge at gmail.com
Mon Jun 30 03:41:39 CEST 2008

Hi everyone,

In Python, the humble colon (:) has multiples uses:

1. as a signal to indentation increase, signaling a block of code, such as
1a) for function or class definitions
1b) for while/for/if/elif/else blocks
1c) for try/except/finally blocks

In these cases, the majority opinion (to which I subscribe) is that
using a colon increases readability.  I am NOT suggesting to removing
the colon in those instances.

However, the colon has also some other uses.

2. in slices [a:b:c]
3. in dict assignments {a:b}
4. in lambda assignments  (lambda x: x+1)

I would argue that, in these last three examples, there might be better choices.
(some of these choices have been inspired by reading

I don't expect the following suggestions to immediately convince
everyone (or anyone!) ... but, at least they will be on record.


I would argue that, the usual slicing notation would be more readable
if it were as follows:

[a -> b; c]

[1:10:2] would become [1 -> 10; 2]
[1:10]  would become [1 -> 10]

The "shorter" combinations would not gain in terms of readability;
they would be as follows:

[ :10 : 2] would become [10; 2]
[ :10]  would become [10;]
[:: -1] would become [; -1]
[:] would become [;]

If such a change were to be made, an second slicing notation, *with a
different meaning*,  could be introduced:

[a => b; c]

This would be an inclusive range, i.e.

[a => b] is equivalent to [a -> b+1]

dict assignments

Here again, I would argue that using "->" instead of ":" would make
the code more readable - at least for beginners.

numbers = {'one' -> 1, 'two' -> 2}  instead of
numbers = {'one': 1, 'two': 2}

lambda assignments

Once again, same choice.

lambda x -> x+1
is, I think, more readable than
lambda x: x+1

(but perhaps the last two [dicts and lambda] largely depends on the
font choice...)

Other considerations:

If "->" were to be adopted for dict or lambda assignments, then the
"naturalness" of their choice for slices would be reduced.  An
alternative might be inspired from the mathematical notation

[a, ..., b; c]

I realize that this is "much" longer than [a: b: c].

Final comment:

 I have seen other alternatives for simple slices suggested in the past such as
[a..b] and [a...b] which would be the equivalent of [a->b] and [a=>b];
however, the extra "." might sometimes be difficult to read, whereas
the difference between "->" and "=>" is much easier to see.



More information about the Python-ideas mailing list