1
votes

I am not able to execute the following code in python: (Sorry if this is a noob question, but I'm new)

    def main(jsonIn):
        print("MAIN")
        print(data["host"])
    
    if __name__ == '__main__':
        logger.log("Loading configuration File.")
        with open('untitled_1.json') as configFile:
                data = json.load(configFile) #HAS 3 TAB SPACES(1[IF STATEMENT]+2[WITH])
                print(data)
                main(data)
    else:
        print("This code does not support being imported as a module")

It gives me the following error:

    File "file.py", line 14
        with open('untitled_1.json') as configFile:
                                                  ^
    TabError: inconsistent use of tabs and spaces in indentation

What is the reason for this? How can I resolve this?

1
Some of your whitespace is tabs and some of it is spaces... You need to have consistent whitespaceAK47
Recommended, though not required, convention is to use 4 spaces for each indentation, 0 tabs.jpp
Note that this error is quite new, before, you could mix -tab-tabCODE and -space-spaceCODEBenoît P
Python 3 doesn't allow mixed indentation, even if it would have been otherwise "correct" in Python 2, because visually it is too hard to tell if the indentation is correct or not.chepner
I didn't know you couldn't mix white spaces and tabs, my bad!Tarun Gopalkrishna

1 Answers

0
votes

From the documentation:

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

You state the body of the with statement is indented with 3 tabs. If that is true, it would appear the line with with itself is indented with 4 spaces. That means that if tab stops were set to just a single space each, the body of the with statement would no longer be indented relative to the first line, resulting in the TabError.

Consider this code (with tabs replaced by a $):

for y in [1]:
    for x in [1,2,3]:
        if x == 2:
            print("even")
$else:
$    print("odd")

If your tab stop was set to 8 characters, this would look like a for loop that contains an if/else statement. If the tab stop was set to 4 characters instead, it would look like a for loop with an else clause. Other tab stops would look like invalid uses of indentation.

Python 2, by contrast, would replace tabs with spaces during parsing so that the indentation was a multiple of 8, and only then determine if the resulting indentation was consistent. This could lead to unintended indentation errors, as code could still parse but have a behavior different from its "visible" indentation. For example, the preceding example would be accepted by Python 2 as in if statement with an else clause, even though in an editor using tab stops of 4 spaces it would look like the else went with the for.