I hate you all

Ian Kelly ian.g.kelly at gmail.com
Fri Apr 5 18:42:15 EDT 2013


On Fri, Apr 5, 2013 at 4:04 PM,  <terminatorul at gmail.com> wrote:
> They say so, but python does not work that way. This is a simple script:
>
> from unittest import TestCase
>
> class SvnExternalCmdTests(TestCase) :
>     def test_parse_svn_external(self) :
>         for sample_external in sample_svn_externals :
>             self.assertEqual(parse_svn_externals(sample_external[0][0], sample_external[0][1]), [ sample_external[1] ])
>
> And at the `for` statement at line 5 I get:
>
> C:\Documents and Settings\Adrian\Projects>python sample-py3.py
>   File "sample-py3.py", line 5
>     for sample_external in sample_svn_externals :
>                                                 ^
> TabError: inconsistent use of tabs and spaces in indentation
>
>
> Line 5 is the only line in the file that starts at col 9 (after a tab). Being the only line in the file with that indent level, how can it be inconsistent ?

The "def" line has four spaces.  The "for" line then has a hard tab.
This is ambiguous.  If the hard tab is assumed to have a width of four
spaces, then they are at the same indentation level.  If it is assumed
to have a width of eight spaces, then they are not.

Python 2 resolved this ambiguity by assuming that a hard tab was
simply equivalent to four or eight spaces (I don't remember which).
The problem with assuming this is that the assumption made by Python
does not necessarily match the tab width selected by the user, with
the result that lines that *look* like they are at the same
indentation level might actually be different (and vice-versa),
leading to hard-to-find bugs.

Python 3 instead resolves this ambiguity by not allowing it.

In the code above, because the "def" line has four spaces, the
indentation of the "for" line that is subordinate to it needs to also
start with four spaces (and then you can continue the indentation with
tabs or spaces as you prefer).  Because the line after the "for" line
is subordinate to it, it also then needs to begin with the same exact
indentation used by the "for" line (in the sample provided, it
currently does).

My suggestion: choose to use either all tabs or all spaces within a
file, and then you won't have this problem.



More information about the Python-list mailing list