Can you mix tabs and spaces in python?

Created on 2019-10-16 08:00 by Mikko Rantalainen, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (6)
msg354779 - (view)Author: Mikko Rantalainen (Mikko Rantalainen)Date: 2019-10-16 08:00
Contrary to PEP-8 (https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) claiming "Python 3 disallows mixing the use of tabs and spaces for indentation", in reality Python 3 allows mixing tabs and spaces without warnings or errors. For example (with all spaces replaced with middle dot and all spaces replaced with a short arrow):

#!/usr/bin/python3
for·i·in·range(2):
··for·j·in·range(3):
➧··for·k·in·range(4):
·➧···print(i,j,k,sep=",")

Either the PEP-8 should be fixed or the parser/compiler should be fixed. 

The current behavior seems a bit unstable because the exact order of spaces and tabs causes "TabError: inconsistent use of tabs and spaces in indentation" to appear more or less random.

I'd prefer python3 to require that *all whitespace* at the start of the all the lines is tabs for the whole file or spaces for the whole file. And first indented line sets the preference for the whole file.

(Personally I'd prefer tabs contrary to PEP-8 language but this bug is not about the preference. This is PEP-8 claiming things that are not true.)

$ python3 --version
Python 3.5.2
msg354780 - (view)Author: Eric V. Smith (eric.smith) *
Can you mix tabs and spaces in python?
Date: 2019-10-16 08:05
I can verify this on 3.7.4.
msg354788 - (view)Author: Steven D'Aprano (steven.daprano) *
Can you mix tabs and spaces in python?
Date: 2019-10-16 08:57
I believe that the interpreter only requires that each block is consistent, not that all blocks in a module are consistent.
msg354791 - (view)Author: Serhiy Storchaka (serhiy.storchaka) *
Can you mix tabs and spaces in python?
Date: 2019-10-16 09:25
Thank you for your report Mikko. Yes, the heuristic used in Python 3 is unable to catch all inconsistencies in using tabs and spaces.

Such bug was already reported early. There should be an open issue.
msg354795 - (view)Author: Karthikeyan Singaravelan (xtreak) *
Can you mix tabs and spaces in python?
Date: 2019-10-16 11:30
Seems related issue24260
msg354796 - (view)Author: Eric V. Smith (eric.smith) *
Can you mix tabs and spaces in python?
Date: 2019-10-16 11:32
Thanks, Serhiy. This has been reported in 24260, so I'm closing this issue.
History
DateUserActionArgs
2022-04-11 14:59:21 admin set github: 82677
2019-10-16 11:32:00 eric.smith set status: open -> closed
superseder: TabError behavior doesn't match documentation
messages: + msg354796

type: behavior
resolution: duplicate
stage: resolved

2019-10-16 11:30:15 xtreak set nosy: + xtreak
messages: + msg354795
2019-10-16 09:25:58 serhiy.storchaka set nosy: + serhiy.storchaka
messages: + msg354791
2019-10-16 08:57:31 steven.daprano set nosy: + steven.daprano
messages: + msg354788
2019-10-16 08:05:23 eric.smith set nosy: + eric.smith
messages: + msg354780
2019-10-16 08:00:10 Mikko Rantalainen create

/ @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

Can you mix tabs and spaces in python?

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

Can you mix tabs and spaces in python?

Does Python use tabs or spaces?

Tabs or Spaces? Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs. Python disallows mixing tabs and spaces for indentation.

How do I make multiple tab spaces in Python?

The expandtabs() character replaces the '\t' with whitespace until the next tab stop. The position of '\t' is 3 and the first tab stop is 8. Hence, the number of spaces after 'xyz' is 5. The next tab stops are the multiples of tabsize .

How do you fix inconsistent tabs and spaces in Python?

To solve the error, remove the whitespace and only indent the lines in the code block using tabs or using spaces.

How many spaces is a \t Python?

In Java, a tab is two spaces, while in Python, it's one.