Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python def without Indentation

Tags:

python

There are multiple occurrences of following format(note there is no indentation after def lines) in a source file I have:

def sendSystemParms2(self, destAddress, subid, state):

raw = sysparms_format2.build(Container(
length = 0x0D,
command = MT_APP_MSG_CMD0))

def method2(parm2):
print parm2

and it's working and running. I am confused. Any hints? I can't upload an image due to being new and not having enough reputations but I can show the proof.

like image 404
doubleE Avatar asked Jun 13 '26 11:06

doubleE


1 Answers

You have a file that uses a mixture of tabs and spaces.

Python expands tabs to eight spaces, but you are looking at the file in an editor that uses a tabstop size of four spaces.

The function bodies use tabs for the indentation, but the def lines use 4 spaces instead. As such as far as Python is concerned the method bodies are indented correctly.

If I set my text editor to using tabs with a size of 8 spaces, and then select the text to have the editor highlight tabs, I see:

source code with indentation highlighted

The lines indicate tabs.

This is one of the reasons you should not be using tabs for indentation at all. The Python style guide recommends you use only spaces for indentation. In Python 3, mixing tabs and spaces like this is a syntax error.

You can tell Python 2 to raise TabError for this mix of tabs and spaces as well, by running Python with the -tt command line switch:

-t
Issue a warning when a source file mixes tabs and spaces for indentation in a way that makes it depend on the worth of a tab expressed in spaces. Issue an error when the option is given twice (-tt).

like image 179
Martijn Pieters Avatar answered Jun 16 '26 03:06

Martijn Pieters