Brad
Brad

Reputation: 6342

why does this throw indentation error?

for bucketLabel, eventList in test_source_json.iteritems(): 
    if bucketLabel == "spotlight": 
        for event in eventList: 
            try: 
                for key in source_keys: 
                    if key not in event: 
                        if key not in responseDictionary[currentTestName][url]: 
                            responseDictionary[currentTestName][url][key] = list()
                        responseDictionary[currentTestName][url][key].append(event)
            except: 
                exc_type, exc_obj, exc_tb = sys.exc_info()
                logging.info("caught exception %s, and obj %s at line number %s" % (exc_type, exc_obj, exc_tb.tb_lineno))
                continue    

This code throws an indentation error at line 4 try: http://repl.it/N7W illustrates the error

Totally confused as to why.

Upvotes: 2

Views: 696

Answers (3)

abarnert
abarnert

Reputation: 366053

The problem—as it often is in cases like this—is that you're mixing tabs and spaces.

Lines 2 and 3 are indented with tabs; line 3 starts with two tab characters. That presumably looks like 8 spaces in your text editor, but as far as Python is concerned, it's 16 spaces.

Line 4 is indented with 12 spaces. So, in your editor, it looks more indented than line 3. But to Python, it's less indented. Hence the error.

The solution is to always use spaces, never tabs. (Alternatively, you can always use tabs instead, just so long as you don't mix them… but always spaces is easier and better in many ways.)

Most editors can be configured to do this—and to show tabs distinctly differently from spaces. The ones that can't (like Notepad) probably shouldn't be used for programming.

You should also run Python with the -t or -tt flag to diagnose IndentationErrors, because it will tell you that you're using tabs and spaces inconsistently. The tabnanny module/script can also be helpful.

Upvotes: 4

Frank Riccobono
Frank Riccobono

Reputation: 1063

Python requires that you use either tabs or spaces for indentation and not both. The official Python recommendation is to use four spaces rather than a tab, but what's more important is you must use the same on each line.

Upvotes: 2

mhlester
mhlester

Reputation: 23251

you're using tabs instead of spaces on that line

Upvotes: 5

Related Questions