Tabs vs spaces - the definitive guide 🤣

Python indentation

[rating: beginner]

Python is notorious for its “indentation is syntax” approach. Coming from C/C++ I definitely didn’t like it at first.

Sometimes it’s still aggravating - especially when I’ve forgotten or improperly indented something & ended up with strange errors. Largely I’ve gotten used to it, and often quite like it. At least there can be fewer arguments about code style because indentation has to be what it is, rather than some stylistic choice.

Indentation is defined by the amount of whitespace at the beginning of a line. It can even be different whitespace characters throughout a single source file, as long as the number of characters for each indentation level is the same throughout the file.

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

Python documentation
# Module level indentation (zero whitespace).
x = 3.14

def do_something(a):
  # One level indentation inside the function.
  # I'm using 2 space characters in this example.
  b = a + 2
	
  if b < a:
    # Second level indentation inside if statement 
    # inside function.
    # This `print` statement is only executed when the 
    # condition evaluates as `True`.
    print("b < a")
		
  # Returning to one level indentation continues.
  # This `print` statement is always executed 
  # after evaluation of the `if` statement.
  print("we did something!")

However it is recommended that uniform whitespace characters are used throughout a file - and by extension throughout a project.

Technically, using both <space><tab> & <tab><space> are valid indents. I strongly recommend you don’t do this!

For the most part, the various formatting tools seem to have settled on “4 space characters” for an indent level. Although I have seen some VSCode configurations that seemed to be using a single tab character instead. A bit irritating when those are committed to source control.

Using formatting tools such as isort & black should eliminate these problems & maintain consistency.

Python documentation:

Reply

or to participate.