Using the Python Interpreter as a Reference
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Nov 29 03:04:14 EST 2011
On Tue, 29 Nov 2011 12:49:49 +1100, Chris Angelico wrote:
> On Tue, Nov 29, 2011 at 11:54 AM, DevPlayer <devplayer at gmail.com> wrote:
>> To me, I would think the interpreter finding the coder's intended
>> indent wouldn't be that hard. And just make the need for consistant
>> spaces or tabs irrevelent simply by reformatting the indent as
>> expected. Pretty much all my text editors can.
>
> The trouble with having a language declaration that "a tab is equivalent
> to X spaces" is that there's no consensus as to what X should be.
> Historically X has always been 8, and quite a few programs still assume
> this. I personally like 4. Some keep things narrow with 2. You can even
> go 1 - a strict substitution of \t with \x20. Once you declare it in
> your language, you immediately break everyone who uses anything
> different.
Why should we enforce how many spaces a tab is set to? That is literally
only visible to the editor, not the compiler. (Unless the parser is
particularly stupid and merely substitutes X spaces for a tab every time
it sees one.)
Mixed spaces and tabs in an indent are ambiguous, and so raises
SyntaxError (or at least it *should* raise SyntaxError). But separate
code blocks can use different absolute indent levels without ambiguity,
so long as the relative indentation is consistent:
def ham(): # tab stops at 4 and 8
do(a)
do(b)
if c:
do(c)
else:
do(d)
def spam(): # tab stops at 8 and 12
do(a)
do(b)
if c:
do(c)
else:
do(d)
There is no meaningful difference in indentation between ham and spam
above. In either case, I could replace spaces with tabs to get the same
relative indents regardless of the absolute indentation.
I can appreciate the aesthetic argument that *within a single file*,
indentation should be consistent. But it's not logically necessary for
the parser: it need only be consistent within a single code unit
(function or class usually). In other words: syntax should only care
about relative indentation, absolute indentation belongs as a coding
standard.
--
Steven
More information about the Python-list
mailing list