Mixing Tabs & Spaces

/ @treyhunner

Indentation

  • Programmers use indentation to make code readable
  • Python uses indentation to define code blocks
  • Python allows either tabs or spaces for indentation
  • Why not both? 😈

Some programmers just want to mix tabs and spaces

Indentation doesn't always matter


def flatten(matrix):
  return [
            n for row
 in matrix for n
       in row
     ]
              
def len_or_none(obj):
   try:
         return len(obj)
   except TypeError:
     return None

Same block? Indentation matters.


def guess_number():
  while True:
     guess = input('Guess: ')
    if guess == '4':
        break
              
def len_or_none(obj):
  try:
      return len(obj)
    except TyperError:
      return None

Indentation rules for each line of code

  1. Same block: last line's indentation level
  2. Outer block: a previous less-indented level
  3. New block: more indented than current indentation

What about tabs and spaces?

  • Typewriters: tab key moves the cursor to the next tab stop
  • In Python, there's a tab stop at every 8 characters
  • 1 tab character = number of spaces until the next tab stop

Tab stops are 8 characters


def guess_number():
    while True:
	guess = input('Guess: ')
	if guess == '4':
	    break
              

def guess_number():
    while True:
        guess = input('Guess: ')
	if guess == '4':
	    break
              

Tabs: not always 8 spaces


def guess_number():
    while True:
	guess = input('Guess: ')
	if guess == '4':
	    break
              

def guess_number():
    while True:
	guess = input('Guess: ')
    	if guess == '4':
	    break
              

def progressively_more_spaces():
 	print("let's add one more space to the beginning...")
  	print("of each line.")
   	print("The effective indentation is the same")
    	print("even though we're adding more spaces.")
     	print("Each tab represents only the spaces needed")
      	print("to get to the next 8 character tab stop.")
       	if "your editor doesn't use 8 character tabs":
        	print("you may have trouble reading this code.")
         	print("Python uses 8 character tab stops")
          	print("so we also use 8 character tab stops.")
           	print("This way we can mix spaces and tabs")
            	print("without any worries about broken code.")
             	print("Mixing tabs and spaces can be fun")
              	print("but beware!")
               	while "you could write code like this":
                	print("It's probably best not to.")
              

Configure your editor


# http://editorconfig.org
[*.py]
indent_size = 4
tab_width = 8
indent_style = tab
          

Don't use Python 3


$ python3 examples/demo.py
  File "examples/demo.py", line 3
    print("of each line.")
                         ^
TabError: inconsistent use of tabs and spaces in indentation
          

PEP 373

End Of Life for Python 2.7: 2020

Don't mix tabs and spaces

Trey Hunner / @treyhunner

Python trainer, on-site & remote
http://truthful.technology