Python and whitespace

I tried umpteen possibilities why my Python code would not run. In the end, by juggling text editors, I discovered that the whitespace before “return” was a tab, not spaces. All the other whitespace was space characters. How could I have detected this earlier?

By this…

… I’m assuming that you mean you can’t “see” where the spaces and tabs are or even if you’re using tabs or spaces?

Any text editor worth the bother of keeping around (or an IDE that has a builtin code editor), will have an option to view white space and (often times) will illustrate a space as a . and a tab as a →

You should also be able to set an option to have any tabs be replaced as a number of spaces; typically four. Once you have that kind of a setup, one does not need to have such illustrated, rather one can trust that spaces are being used throughout ones code. So, don’t mix tabs and spaces; simply use spaces only and you should have no further issues, such as the ones you describe.

For reference, please see:

Also, any editor that knows anything about Python can simply give a highlight when there’s a problem.

def spam():
    print("Spam")
	return 42

Here’s SciTE:
Screenshot_2023-08-02_00-54-07
Here’s Visual Studio Code:
Screenshot_2023-08-02_00-56-11

(I have SciTE set to show tabs wider than I have VS Code set to show them, so they look a bit different, but either way the marker is there.)

If your editor made it impossible for you to distinguish lowercase l from the digit 1, would you say that Python is “barking mad” for giving them different meanings? It’s frankly rather offensive to blame the language for a fault in your tools. Either fix the tools you have, or get better tools.

I don’t understand why you had such a problem fixing the error. Python (since at least 3.8 and likely much earlier) tells you what the problem is and where. In 3.13, it changed ‘SyntaxError’ to ‘TabError’ to be even more specific.

>>> def f():
...     a = 3
...     print(a)
  File "<stdin>", line 3
    print(a)
TabError: inconsistent use of tabs and spaces in indentation

Copying from Command Prompt copies the tab before the print as spaces, but in an editor, putting the cursor at the beginning of line 3 and moving right jumps the cursor 4 spaces, making it clear that there is a tab, not 4 spaces.

IDLE does not have a ‘show tabs’ feature partly because of limitations of tcl/tk Text widgets, but it does have a Convert Tabs feature, and for Syntax/Tab errors, it highlights the tab spaces in red.

1 Like

This isn’t a request for assistance, what exactly was your purpose or hoped-for expected outcome with this message?

1 Like

My apologies for my outburst. It was not helpful.

2 Likes