5.2. Learning to Love Significant Indentation

The most common concern I hear about Python from programmers com- ing from other languages is that Python’s significant indentation (often mis- takenly called significant whitespace) is weird and unfamiliar. The amount of indentation at the start of a line of code has meaning in Python, because it determines which lines of code are in the same code block.

Grouping blocks of Python code using indentation can seem odd, because other languages begin and end their blocks with braces, { and } . But programmers in non-Python languages usually indent their blocks too, just like Python programmers, to make their code more readable. For example, the Java programming language doesn’t have significant inden- tation. Java programmers don’t need to indent blocks of code, but they often do anyway for readability. The following example has a Java function named main() that contains a single call to a println() function:

// Java Example public static void main(String[] args) { System.out.println(“Hello, world!”); }

This Java code would run just fine if the println() line weren’t indented, because the braces, rather than the indentation, are what mark the start and end of blocks in Java. Instead of allowing indentation to be optional, Python forces your code to be consistently readable. But note that Python doesn’t have significant whitespace, because Python doesn’t restrict how you can use nonindentation whitespace (both 2 + 2 and 2+2 are valid Python expressions).

Some programmers argue that the opening brace should be on the same line as the opening statement, while others argue it should be on the following line. Programmers will argue the merits of their preferred style until the end of time. Python neatly sidesteps this issue by not using braces at all, letting Pythonistas get back to more productive work. I’ve come to wish that all programming languages would adopt Python’s approach to grouping blocks of code.

But some people still long for braces and want to add them to a future version of Python—despite how unpythonic they are. Python’s future module backports features to earlier Python versions, and you’ll find a hid- den Easter egg if you try to import a braces feature into Python:

>>> from __future__ import braces
SyntaxError: not a chance

I wouldn’t count on braces being added to Python any time soon.