2

I am new to python and trying to learn an unfamilar code base. I want to add a print statement just below the def line. But every time I do so for one of these very short methods I get an indentation error.

def rename(self, old, new):
    #print 'this will bring an error if left uncommented'       
    return os.rename(self._full_path(old), self._full_path(new))

How can I add a print statement to a short method like this?

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • 3
    This "should be" no problem at all. Make sure you're not mixing spaces with tabs! If it's code you didn't write, the author may have had a different idea than your editor does about what a tab means. I prefer all spaces. – Tim Peters Dec 01 '13 at 05:04
  • @TimPeters how many spaces equals a tab? – bernie2436 Dec 01 '13 at 05:04
  • 1
    That's the point: there is no defined answer to that. Unix programmers usually think "8", Windows programmers often think "4". That's why tabs suck in contexts where whitespace is significant. **Try something.** All I can tell from here is that the sample you posted used all spaces for indentation. That's fine. There's no SyntaxError when I try it. – Tim Peters Dec 01 '13 at 05:07
  • @akh2103 Which editor are you using? – thefourtheye Dec 01 '13 at 05:10
  • 1
    And which version of Python are using? If you're using Python 3, `print` is *not* a statement there - in Python 3 you need to use `print` as a function instead. – Tim Peters Dec 01 '13 at 05:11
  • Full error message / stack trace please... To avoid guesses about tabs, spaces, python versions or your grandmother's shoe size. – Hyperboreus Dec 01 '13 at 05:31
  • See question and answer to [_elif giving syntax error python?_](http://stackoverflow.com/questions/16745740/elif-giving-syntax-error-python) – martineau Dec 01 '13 at 05:58

2 Answers2

6

A tab is a tab character (just like \n is a newline character), you can configure most editors to replace a tab character with a certain number of spaces.

The convention in Python is to indent by four spaces and to use spaces instead of tabs. This is the recommendation; but people tend to do what they please.

It is most likely that the code is indented by tabs and you are using spaces. @TimPeters wrote reindent.py that will take a Python file and convert tabs into spaces.

There are other tools as well. Most editors have a function that can do this, if the editor is Python aware they may have a specific function for just this. For example has a "Convert Indents" menu option under Edit.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
-1

Try this code:

def rename(self, old, new):
    print('this will bring an error if left uncommented')       
    return os.rename(self._full_path(old), self._full_path(new))

Whenever I have trouble with the print keyword, I can usually solve it by using print() instead.

DJ8X
  • 385
  • 4
  • 9