Shubham
Shubham

Reputation: 979

porting Python 2 syntax to Python 3

I'm trying to run the following code in python3, but it has been written for I'm pretty sure python2:

f = open(filename, 'r')
self.lines = f.readlines()
f.close()
if self.lines[-1] != "\n" :
    self.lines.append("\n")

But I'm getting the following error:

  File "randline.py", line 32
    if self.lines[-1] != "\n" :
                              ^
TabError: inconsistent use of tabs and spaces in indentation

Can you help me figure out the correct syntax?

Upvotes: 0

Views: 4756

Answers (1)

Lennart Regebro
Lennart Regebro

Reputation: 172219

Python 2 allows you to mix spaces and tabs. so you can have indentation like:

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[this is a tab it counts like eight spaces             ][space][space]print(each)
[space][space][space][space][space][space][space][space]print("Done!")

Line 2 and line 4 will in Python 2 have the same indentation level, but line 2 will do it with a tab, and line 4 will do it with spaces. Printed to the console, it will look like this:

def foo()
        for each in range(5):
          print(5)
        print("Done!")

But most editors allow you to set how many spaces a tab should be. Set it to four, and you get this:

def foo()
    for each in range(5):
      print(5)
        print("Done!")

The indentation is still the same, but now it looks like the indentation is wrong!

Python 3 therefore do not allow the same indentation level (ie line 2 and 4) to be indented in different ways. You can still mix tabs and spaces, but not in the same indentation level. This means that

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[this is a tab it counts like eight spaces             ][space][space]print(each)
[this is a tab it counts like eight spaces             ]print("Done!")

will work, and so will

def foo():
[this is a tab it counts like eight spaces             ]for each in range(5):
[space][space][space][space][space][space][space][space][space][space]print(each)
[this is a tab it counts like eight spaces             ]print("Done!")

The only way to make that the only way you can make the indentation look weird is of you set a tab to be more than eight spaces, and then the indentation not only looks obviously incorrect, you'll notice that a tab will indent 12 spaces (in the below example) so you realize you insert a tab, and not four spaces.

def foo():
            for each in range(5):
          print(each)
            print("Done!")

Of course, the solution to all your problems is as written in the comments, to never use tabs. I'm not sure why Python 3 still allows tabs at all, there is no good reason for that, really.

Upvotes: 6

Related Questions