Search code examples
pythonindentation

The indentation in Python code appears to be incorrect but the code runs


There is no IndentationError or TabError nor am I asking how to fix any such error. The program runs as intended.

I received some Python code to maintain. How can this possibly work and why it crashes with unindent error only if I modify the internals of the inner for loop?

        for m in range(len(Model)):
        if param==1:
            m=m-1

            parFlag = 0
            for s in range(len(PSets)):
                if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:
                    parFlag = 1

It looks even stranger now when I am entering it here:

enter image description here

I think it can have something to do with tabs, but I don't know much about them except I try to avoid them wherever possible.


Solution

  • Indeed, the code is mixing tabs and spaces:

    >>> from pprint import pprint
    >>> pprint('''\
    ...                     for m in range(len(Model)):
    ...                 if param==1:
    ...                     m=m-1
    ... 
    ...                 parFlag = 0
    ...                 for s in range(len(PSets)):
    ...                     if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:
    ...                         parFlag = 1
    ... '''.splitlines())
    ['    \t\tfor m in range(len(Model)):',
     '\t\t    if param==1:',
     '\t\t    \tm=m-1',
     '',
     '        \t    parFlag = 0',
     '        \t    for s in range(len(PSets)):',
     '\t                if Parameter.lower() in self._Sets._P_ModelVars[Model[m]][PSets[s]]:',
     '\t                    parFlag = 1']
    

    Note all the mix of \t and characters at the start of each line.

    A good text editor will let you replace the tabs with spaces, and also let you set what style should be used when creating new indentations. The Python style guide recommends you stick with only spaces.

    You can detect where spaces and tabs are mixed by running the code with the -tt command line switch:

    python -tt yourscript.py