Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Great Python Indentation Debate

Many discard Python because it uses indentation to denote blocks in a language and non a familiar C-like syntax. I think that's a big mistake.

Indentation is not a burden because the most natural form of the program is an indented one. In languages like PL/1, C  a pretty printer is a must. But if you consistently uses a pretty printer why waist two useful symbols ("{" "}" ) for what can be done with comments.  That means that indentation can be always generated automatically from special comments. But the problem is that it is optional feature, you don't have to use it, but it is highly recommended. You can use pseudo-comments like "#{" and "#}" as substitutes.

In Python adding block-delimiting comments is the optional feature and the use of whitespace is the mandatory feature. Python reversed the priority because whitespace is a better visual aid in understanding the flow of a program. But if you use comments to mark beginning and end of each block and automatic indentation, than it's indentation than really matters. And that's great. It's easy to miss delimiters like "{" and "}" when looking over one screenpage of code.

The problem with indentation is that if block is long it is visually lost, as you do not see on the screen where the block starts. Folding in such cases might help.  So working with large scripting in Python presuppose using pretty advanced editor. Which might be a good thing, as I hate programmers who use nano ;-) 

The choice in Python was in favor of pretty printer and I tend to support it on the basis on usability issues. Languages such as Perl and Tcl made their design decisions based on familiarity with C rather than usability. They simply borrowed the successful C-based notation of using curly braces for blocks (which actually is "one one step forward, two steps back" from PL/1 notation, which served as prototype for C, as Pl/1 allows to close multiple blocks using labels and C does not ). C misses some earlier PL/1 extensions like closing several blocks with one delimiter. Here in Python one get this nice feature for free.

Using white space for indentation creates tricky to debug errors for beginners as they can mix tabs and spaces in the same program and the resulting indentation now depends on congruence of tab setting in Python interpreter and the editor. If the settings are different  on different servers (and they often are) users are in deep trouble and resulting diagnostics is pretty weak, if not to say horrible (Python interpreter should accept iether "tab indented" code or "space indented", but in case both are used it should produce an error, or at least a warning).

So forced conversion of tabs into spaces is a "must" in Python.  This "gotcha" is often missed in Python introductory books. Explanation in python.org is primitive and missed this gotcha:

Why separate sections by indentation instead of by brackets or 'end' - Python Wiki

SEE:Ten things people want to know about Python

Answer
  • In order to separate blocks of code (like for loops, if blocks and function definitions) the compiler / interpreter needs something to tell it when a block ends. Curly braces and end statements are perfectly valid ways of providing this information for the compiler. For a human to be able to read the code indentation is a much better way of providing the visual cues about block structure. As indentation also contains all the information for the compiler, to use both would be redundant. As indentation is better for humans, it makes sense to use that for the compiler too. It has the advantage that Python programs tend to be uniformly and consistently indented, removing one hurdle to understanding other people's code. Python does not mandate how you indent (two spaces or four, tabs or spaces - but not both), just that you do it consistently. Those that get used to the Python way of doing things tend to start seeing curly braces as unnecessary line noise that clutters code. On the other hand, 'the whitespace thing' is possibly the single biggest reason why some developers refuse to even try Python.

[Folklore says that the ABCers in the '80s experimentally determined that significant whitespace has measurable advantages. 'Anyone have documentation for this?]

Additional observation::

  • Among programmers using languages which ignore white space the prevailing conventions are to indent blocks of code to facilitate readability by humans. The exact details of such conventions vary (and are subject to considerable stylistic debate among some programmers). But the general features are ubiquitous, nearly universal: code is rendered mostly in an "outline" format ... with levels of lexical nesting denoted by increasing degrees of indentation. Python merely uses this (nearly universal) convention as part of its syntax which allows it to dispense with other block ending tokens. Some argue that this syntax helps avoid situations where the code doesn't match the apparent intent (when the indentation is subtly inconsistent with the lexical structure). As with the finer points of how code should be indented in white space agnostica languages, that is a point of endless discussion.

 

Also using whitespace for indentation creates some "unforced errors" :

 

See an interesting Slashdot discussion below that shed some additional light on the situation.

Re:Python - so close... (Score:2, Insightful)
by JohnPM on Sunday April 23, @12:48PM EST (#84) (User Info)
The syntactic indenting in Python is actually extremely cool. Ok, so maybe it means that emacs is the only editor it makes sense programming with - but we knew that already right? The main benifit I see to syntactic indenting is that is narrows down the possible range of coding styles. If you think about it, most of the (dare I say) splintering of C/C++/Java coding styles is due to the placement of the { and } symbols. This acts against readability for other developers. It's also less typing.

If you like the keybindings and programmability of Emacs, but don't like its size, try JED which also has a pretty good Python mode, too.

...and yet grounded in its 1950's roots?? Idea! (Score:3, Interesting)
by devphil on Sunday April 23, @12:35PM EST (#79) (User Info)
That's something that seriously bugs me about Python. I have tried over the years to not be a syntax bigot, but Perl loses in this respect. I saw the quip, "Perl -- the only programming language that looks the same both before and after RSA encryption," and it makes perfect sense. Dilbert's joke about a rat dancing on his keyboard and writing a web browser could probably come true in Perl.

Python is a big, big win. But the required indentation just stupifies me. I feel like I'm writing a FORTRAN 77 program, indenting to the correct place so that the compiler/interpreter can find the right column of the punched card...

I'm not a big fan of 1950's cars, clothes, music, or programming languages.

A really useful tool (written in Python or Perl or awk or whatever) would read in a "Braced Python" file, remove the {}'s and redo the indentation inside them, and then write out a syntactically-correct file. (For bonus points, play some 50's tunes while it's converting.)

This would aid the transition from free-form languages like C++ (and FORTRAN 95...). It's enough to introduce new ideas; don't beat the user over the head with personal indentation preferences at the same time.

Re:...and yet grounded in its 1950's roots?? Idea! (Score:4, Insightful)
by eff on Sunday April 23, @01:21PM EST (#88)  (User Info) http://www.pythonware.com/people/fredrik
A really useful tool (written in Python or Perl or awk or whatever) would read in a "Braced Python" file, remove the {}'s and redo the indentation inside them, and then write out a syntactically-correct file.

such a tool comes with the standard python distribution (look for pindent in the Tools directory).

(there's also something called corbascript, which is pretty much python with braces...)

real python programmers tend to use python-aware editors, but that's another story...

Re:Python - so close... (Score:1)
by mcdonc ([email protected]) on Sunday April 23, @11:53PM EST (#122)
(User Info) http://www.digicool.com
That's completely false. Perl certainly has strong OO syntax. Perl, in fact, has much stronger OO than Python. A couple of reasons are that in Perl you have privacy, and also because in Perl its much easier to generate metaclasses.

I write python all day long every day. I used to do same for perl. This statement is pretty darn funny. As my coworker jeffrey (with a derisive snort) would say "OO is all about virtual private methods and late bindings" (then bust up laughing).
Re:Python....watch out...(maybe) (Score:2, Informative)
by TresEquis on Sunday April 23, @09:33PM EST (#117)
(User Info) http://www.palladion.com

From what I can tell, they plan on revamping pretty much all of the syntax...and it won't be backwards compatible in the end release.(they do plan on working slowly up to it, AFIAK)

Nyet, tovarisch. The "backwards compatibility" issue in Python 3000 is mostly likely to bite extension writers, who code to Python's C API; most code written in Python will see very little, if any, compatibility problems.

I don't recall any of the specifics, but maybe they will be integrating the most sought after change....no more tabs and whitespace! ;)

No way, no how, not ever! The use of indentation to indicate block structure is a core feature, there by explicit design, to increase readability (you probably indent your C/C++, Java, or Perl to match the block structure already, right? so just lose the "noise" characters, and let the parser read the indentation). The issue has been repeatedly raised on comp.lang.python, mostly by people who haven't actually used Python for anything significant. As for the dreaded whitespace-eating nanoviruses, those have been discussed extensively on the newsgroup, as well.

Re:Python....watch out...(maybe) (Score:1)
by soulhuntre on Monday April 24, @12:49AM EST (#127)
(User Info) http://www.virtualchemy.com
"...so just lose the "noise" characters..."

Sorry, but no. This is simply too much for a number of reasons...
  1. positionally dependant languages are simply silly.
  2. my programmers work in perl and C++ as well, there is no reason to inflict a radically different syntax system on them
  3. for those of us with long programming histories, those {} characters are important visual cues in the code we read, I have no intention of turning off reflexes I learned over the last 20 years or so just to satisfy someone's syntax egotism.

Ken

Re:Python....watch out...(maybe) (Score:1)
by CoderDevo on Monday April 24, @04:57AM EST (#130)
(User Info)
Your argument falls apart when you realize that Python is designed to be a language that is for newbies, is for oldies, is here to stay and will create careers for Python programmers.

Answers:

1) positionally dependant languages are simply silly.

No paradigm is "simply silly." It either works, or it doesn't. In the context of Python, positional dependence helps define the language. Have you ever taken over someone elses code? This enforces easy to read, easy to maintain code.

2) my programmers work in perl and C++ as well, there is no reason to inflict a radically different syntax system on them

Not much faith in your programmers. I see that if they know Perl well, then there may be no need to use Python. However, I was given the choice of learning a modern scripting language. I already knew Borne shell and awk. After much research, I decided on Python. My C++ is strong and Python was an obvious fit for my skills and style. I am still happy with the decision.

3) for those of us with long programming histories, those {} characters are important visual cues in the code we read, I have no intention of turning off reflexes I learned over the last 20 years or so just to satisfy someones syntax egotism.

These "visual cues" are learned. Just as positional dependence is learned. It's just a different paradigm, not necessarily better or worse.(better) :)


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Nov 06, 2017] Indentation Error in Python - Stack Overflow

Nov 06, 2017 | stackoverflow.com
I can't compile because of this part in my code:
    if command == 'HOWMANY':
        opcodegroupr = "A0"
        opcoder = "85"
    elif command == 'IDENTIFY':
        opcodegroupr = "A0"
        opcoder = "81"

I have this error:

Sorry: IndentationError: ('unindent does not match any outer indentation level', ('wsn.py', 1016, 30, "\t\telif command == 'IDENTIFY':\n"))

But I don't see any indentation error. What can be the problem?

Martijn Pieters ,Feb 20, 2013 at 11:54

You are mixing tabs and spaces.

Find the exact location with:

python -tt yourscript.py

and replace all tabs with spaces. You really want to configure your text editor to only insert spaces for tabs as well.

poke ,Feb 20, 2013 at 11:55

Or the other way around (depends on your personal preference) – poke Feb 20 '13 at 11:55

poke ,Feb 20, 2013 at 12:02

@MartijnPieters If you use tabs, you have tabs, so you do not need to care about its visual presentation. You should never mix tabs and spaces, but apart from that, just choose one and stick to it . You are right, it's a never-ending debate; it totally depends on your personal preference -- hence my comment. – poke Feb 20 '13 at 12:02

neil ,Feb 20, 2013 at 12:02

I have never understood why you would want to use spaces instead of tabs - 1 tab is 1 level of indent and then the size of that is a display preference - but it seems the world disagrees with me. – neil Feb 20 '13 at 12:02

Martijn Pieters ♦ ,Feb 20, 2013 at 12:13

@poke: That's very nice, but in any decent-sized project you will not be the only developer. As soon as you have two people together, there is a large chance you'll disagree about tab size. And pretending that noone will ever make the mistake of mixing tabs and spaces is sticking your head in the sand, frankly. There is a reason that every major style guide for OSS (python or otherwise) states you need to use spaces only . :-) – Martijn Pieters ♦ Feb 20 '13 at 12:13

geoffspear ,Feb 20, 2013 at 12:22

There should be one, and preferably only one, obvious way to do it. Following the style of the python codebase itself is obvious. – geoffspear Feb 20 '13 at 12:22

[Nov 06, 2017] Python Myths about Indentation

Nov 06, 2017 | www.secnetix.de

Python: Myths about Indentation

Note: Lines beginning with " >>> " and " ... " indicate input to Python (these are the default prompts of the interactive interpreter). Everything else is output from Python.

There are quite some prejudices and myths about Python's indentation rules among people who don't really know Python. I'll try to address a few of these concerns on this page.


"Whitespace is significant in Python source code."

No, not in general. Only the indentation level of your statements is significant (i.e. the whitespace at the very left of your statements). Everywhere else, whitespace is not significant and can be used as you like, just like in any other language. You can also insert empty lines that contain nothing (or only arbitrary whitespace) anywhere.

Also, the exact amount of indentation doesn't matter at all, but only the relative indentation of nested blocks (relative to each other).

Furthermore, the indentation level is ignored when you use explicit or implicit continuation lines. For example, you can split a list across multiple lines, and the indentation is completely insignificant. So, if you want, you can do things like this:

>>> foo = [
... 'some string',
... 'another string',
... 'short string'
... ]
>>> print foo
['some string', 'another string', 'short string']

>>> bar = 'this is ' \
... 'one long string ' \
... 'that is split ' \
... 'across multiple lines'
>>> print bar
this is one long string that is split across multiple lines

"Python forces me to use a certain indentation style."

Yes and no. First of all, you can write the inner block all on one line if you like, therefore not having to care about intendation at all. The following three versions of an "if" statement are all valid and do exactly the same thing (output omitted for brevity):

>>> if 1 + 1 == 2:
... print "foo"
... print "bar"
... x = 42

>>> if 1 + 1 == 2:
... print "foo"; print "bar"; x = 42

>>> if 1 + 1 == 2: print "foo"; print "bar"; x = 42

Of course, most of the time you will want to write the blocks in separate lines (like the first version above), but sometimes you have a bunch of similar "if" statements which can be conveniently written on one line each.

If you decide to write the block on separate lines, then yes, Python forces you to obey its indentation rules, which simply means: The enclosed block (that's two "print" statements and one assignment in the above example) have to be indented more than the "if" statement itself. That's it. And frankly, would you really want to indent it in any other way? I don't think so.

So the conclusion is: Python forces you to use indentation that you would have used anyway, unless you wanted to obfuscate the structure of the program. In other words: Python does not allow to obfuscate the structure of a program by using bogus indentations. In my opinion, that's a very good thing.

Have you ever seen code like this in C or C++?

/* Warning: bogus C code! */

if (some condition)
if (another condition)
do_something(fancy);
else
this_sucks(badluck);

Either the indentation is wrong, or the program is buggy, because an "else" always applies to the nearest "if", unless you use braces. This is an essential problem in C and C++. Of course, you could resort to always use braces, no matter what, but that's tiresome and bloats the source code, and it doesn't prevent you from accidentally obfuscating the code by still having the wrong indentation. (And that's just a very simple example. In practice, C code can be much more complex.)

In Python, the above problems can never occur, because indentation levels and logical block structure are always consistent. The program always does what you expect when you look at the indentation.

Quoting the famous book writer Bruce Eckel:

Because blocks are denoted by indentation in Python, indentation is uniform in Python programs. And indentation is meaningful to us as readers. So because we have consistent code formatting, I can read somebody else's code and I'm not constantly tripping over, "Oh, I see. They're putting their curly braces here or there." I don't have to think about that.


"You cannot safely mix tabs and spaces in Python."

That's right, and you don't want that. To be exact, you cannot safely mix tabs and spaces in C either: While it doesn't make a difference to the compiler, it can make a big difference to humans looking at the code. If you move a piece of C source to an editor with different tabstops, it will all look wrong (and possibly behave differently than it looks at first sight). You can easily introduce well-hidden bugs in code that has been mangled that way. That's why mixing tabs and spaces in C isn't really "safe" either. Also see the "bogus C code" example above.

Therefore, it is generally a good idea not to mix tabs and spaces for indentation. If you use tabs only or spaces only, you're fine.

Furthermore, it can be a good idea to avoid tabs alltogether, because the semantics of tabs are not very well-defined in the computer world, and they can be displayed completely differently on different types of systems and editors. Also, tabs often get destroyed or wrongly converted during copy&paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.

Most good editors support transparent translation of tabs, automatic indent and dedent. That is, when you press the tab key, the editor will insert enough spaces (not actual tab characters!) to get you to the next position which is a multiple of eight (or four, or whatever you prefer), and some other key (usually Backspace) will get you back to the previous indentation level.

In other words, it's behaving like you would expect a tab key to do, but still maintaining portability by using spaces in the file only. This is convenient and safe.

Having said that -- If you know what you're doing, you can of course use tabs and spaces to your liking, and then use tools like "expand" (on UNIX machines, for example) before giving the source to others. If you use tab characters, Python assumes that tab stops are eight positions apart.


"I just don't like it."

That's perfectly OK; you're free to dislike it (and you're probably not alone). Granted, the fact that indentation is used to indicate the block structure might be regarded as uncommon and requiring to get used to it, but it does have a lot of advantages, and you get used to it very quickly when you seriously start programming in Python.

Having said that, you can use keywords to indicate the end of a block (instead of indentation), such as " endif ". These are not really Python keywords, but there is a tool that comes with Python which converts code using "end" keywords to correct indentation and removes those keywords. It can be used as a pre-processor to the Python compiler. However, no real Python programmer uses it, of course.
[Update] It seems this tool has been removed from recent versions of Python. Probably because nobody really used it.


"How does the compiler parse the indentation?"

The parsing is well-defined and quite simple. Basically, changes to the indentation level are inserted as tokens into the token stream.

The lexical analyzer (tokenizer) uses a stack to store indentation levels. At the beginning, the stack contains just the value 0, which is the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack, and an "INDENT" token is inserted into the token stream which is passed to the parser. There can never be more than one "INDENT" token in a row.

When a line is encountered with a smaller indentation level, values are popped from the stack until a value is on top which is equal to the new indentation level (if none is found, a syntax error occurs). For each value popped, a "DEDENT" token is generated. Obviously, there can be multiple "DEDENT" tokens in a row.

At the end of the source code, "DEDENT" tokens are generated for each indentation level left on the stack, until just the 0 is left.

Look at the following piece of sample code:

>>> if foo:
... if bar:
... x = 42
... else:
... print foo
...
In the following table, you can see the tokens produced on the left, and the indentation stack on the right.
<if> <foo> <:> [0]
<INDENT> <if> <bar> <:> [0, 4]
<INDENT> <x> <=> <42> [0, 4, 8]
<DEDENT> <DEDENT> <else> <:> [0]
<INDENT> <print> <foo> [0, 2]
<DEDENT> [0]
Note that after the lexical analysis (before parsing starts), there is no whitespace left in the list of tokens (except possibly within string literals, of course). In other words, the indentation is handled by the lexer, not by the parser.

The parser then simply handles the "INDENT" and "DEDENT" tokens as block delimiters -- exactly like curly braces are handled by a C compiler.

The above example is intentionally simple. There are more things to it, such as continuation lines. They are well-defined, too, and you can read about them in the Python Language Reference if you're interested, which includes a complete formal grammar of the language.

Indentation Error in Python - Stack Overflow

[Jun 26, 2002] Which is better, python or perl And more importantly, why

Kragen Sitaker [email protected]
Wed, 26 Jun 2002 04:19:08 -0400 (EDT)

This kragen-tol article was published (with some of the mistakes removed) in ;login: this month; I had the following interesting conversation with a reader, which I repost here with his permission.

Date: Thu, 13 Jun 2002 14:32:50 -0700 (PDT)
From: "Simon J. Gerraty" <[email protected]>
Subject: Re: python indent sensitive

Hi,

I was reading your article in ;Login: regarding python cf. perl. In your comments about python being indentation sensitive you assert that anyone who finds this silly is an unthinking moron.

I recall looking at the python web pages some years ago - since python sounded cool, and saw a claim that "there is a very good reason python doesn't use braces", but that reason was never given.

Since you clearly hold that python's indentation sensitivity is a bonus, perhaps you could explain why - with actual reasons that is.

Its possible I'm wrong to think that python would have been a very good language if only it used braces for grouping rather than indentation, but absent something a bit more convincing than "its better", I can only imagine it being a source of hard to track bugs.

Thanks --sjg

Date: Thu, 13 Jun 2002 18:52:15 -0400
From: Kragen Sitaker <[email protected]>
Subject: Re: python indent sensitive
Simon J. Gerraty writes:
> I was reading your article in ;Login: regarding python cf. perl.
> In your comments about python being indentation sensitive you
> assert  that anyone who finds this silly is an unthinking moron.

I haven't seen the printed version yet, but I think I said that certain kinds of "unthinking morons" (your words, not mine) didn't like it, but I specifically said there might be reasons other than being an "unthinking moron" that one might not like it.

Many people who "unthinkingly adhere to stupid traditions" (my words from the article) are quite intelligent.

> Since you clearly hold that python's indentation sensitivity is a
> bonus, perhaps you could explain why - with actual reasons that
> is. 

With braces, I have to say what I mean twice --- once with the braces, so the compiler can understand me, and once with indentation, so humans can understand me. If I get it wrong, I have an unseen bug. As a C, C++, and Perl programmer, I eventually developed very sharp eyes for things like this:

if (foo)
   debug_printf("foo happened\n");
   barf();
do_something_else();
In Python, I don't have to waste my attention on that any more.

Whitespace is a preattentive feature; it is processed by my retina and visual cortex without any conscious attention on my part and very little effort, and I can see *all* of the whitespace in a large visual display in less than a quarter of a second, about the time it takes my eye to move from one spot to another. It is a major benefit to be able to understand the nesting structure of a whole screen or page of source code automatically and with no effort. That is why indentation to show nesting in source code is universal today.

Python simply removes the possibility that your subconscious, preattentive understanding of your program's structure is incorrect. Knowing that a program is written in Python also eliminates the possibility that it is unindented; an unindented C program can be run through 'indent', but an unindented Perl program is a nightmare.

People occasionally suggest that this lack of redundancy will lead to bugs, as a misindented statement won't be noticed later. (Specifically, a statement that should be inside a block being after the block, or vice versa.) I've introduced lots of bugs in programs, and I have kept exhaustive records of the bugs I found in many small programs. I cannot recall any bugs of this nature in my Python or Perl programs, but I have introduced this kind of bug a few times in C and C++ programs, usually in the way shown above.

It is rarely subtle in its effects, but it is often hard to find.

I don't argue that redundancy is always bad, but that in this particular case, the redundancy proves not to be worth its price.

For my thoughts on when redundancy in syntax (and programming languages in general) is a good idea, see http://lists.canonical.org/pipermail/kragen-tol/2002-April/000705.html "Lisp syntax considered insufficiently redundant" and http://www.paulgraham.com/redund.html "Redundancy and Power".


Subject: Re: python indent sensitive
Date: Thu, 13 Jun 2002 17:44:08 -0700
From: "Simon J. Gerraty" <[email protected]>
Hi, I dropped the login address [the original mail was Cc:ed to [email protected]] - since it was wrong anyway :-)
> > Since you clearly hold that python's indentation sensitivity is a
> > bonus, perhaps you could explain why - with actual reasons that
> > is.  
> 
> With braces, I have to say what I mean twice --- once with the braces,
> so the compiler can understand me, and once with indentation, so humans
> can understand me.  If I get it wrong, I have an unseen bug.  As a C,

Hmmm, interesting. I'm thinking more of the case where I put the braces in and the editor does the indenting for me - emacs, no pain at all.

Further, while indentation alone may suffice for a screen's worth of code, I find it inadequate for grossly large blocks of code. Note that I often have to debug programs written by others so the fact that a huge function should be re-organized is orthogonal to understanding what it is doing. Being able to ask a tool like an editor "go show me where this block started" is very handy. Matching braces etc makes this easy.

Now of course it could be the case that there is a decent python mode for emacs that handles all this.

> code automatically and with no effort.  That is why indentation to show
> nesting in source code is universal today.

Sure, but using braces makes it simpler to write tools to munge/analize code. Does python treat a line of code indented with a TAB differently to code indented with spaces?
> it is unindented; an unindented C program can be run through 'indent',
> but an unindented Perl program is a nightmare.

Yep, any unindented code is a nightmare.

> People occasionally suggest that this lack of redundancy will lead to
> bugs, as a misindented statement won't be noticed later.  (Specifically,
> a statement that should be inside a block being after the block, or
> vice versa.)  I've introduced lots of bugs in programs, and I have
> kept exhaustive records of the bugs I found in many small programs.
> I cannot recall any bugs of this nature in my Python or Perl programs,
> but I have introduced this kind of bug a few times in C and C++ programs,
> usually in the way shown above. 

Again, I'm more concerned about code I didn't write. Anything that assists me in analyzing the code for bugs is good.

Anyway, thanks for elaborating on "its better".

--sjg

From: [email protected] (Kragen Sitaker)
Date: Wed, 19 Jun 2002 15:43:00 -0400  (I think)
Subject: Re: python indent sensitive
You write:
> Hmmm, interesting.  I'm thinking more of the case where I put the
> braces in and the editor does the indenting for me - emacs, no pain at
> all.

Well, when you're *writing* code --- typing it out one line after another --- it's usually not a problem, with or without braces. It's when you're *editing* code that the problem comes up. In Emacs, at least, I experience some pain when you're creating or deleting blocks around existing code; sometimes I revert to C-n TAB C-n TAB, but there is of course M-C-\, which requires me to select the affected code first, after having already added or deleted braces. In Python, I typically select the affected code and hit C-c > or C-c <.

I should record an editing session sometime to identify the particular transformations I'm really performing instead of the ones that come to mind.

When you're *reading* code, the braces just take up space without conveying any information not already conveyed by the whitespace.

> Further, while indentation alone may suffice for a screen's worth of
> code, I find it inadequate for grossly large blocks of code.

Meaning that you need both block structure and editor support for it?

> Note that I often have to debug programs written by others so the
> fact that a huge function should be re-organized is orthogonal to
> understanding what it is doing.  Being able to ask a tool like an
> editor "go show me where this block started" is very handy.
> Matching braces etc makes this easy.

Well, unfortunately forward-sexp and backward-sexp don't think Python blocks are sexps, but when I want to know where a block began, I usually move to the end, hit Enter, then hit Backspace a few times. Each Backspace moves me back one indent level (like } in C-mode with auto-mode turned on) and prints a line in the minibuffer telling me where the block I'm closing began. This isn't ideal, but it's usually good enough.

Someone has hacked up an outline minor-mode for Python thet lets you collapse functions and classes; I wish I had something like that for arbitrary blocks.

> Sure, but using braces makes it simpler to write tools to
> munge/analize code.   Does python treat a line of code indented with
> a TAB differently to code indented with spaces?

It treats it as if it had been run through 'expand -8'.

I often find indentation more useful for writing automated tools, too; questions like the following are easier to answer by indentation than by parsing. (They all can get fouled up by Python's multiline strings, though, because those can be arbitrarily indented or outdented.)

You can do shallow processing like this correctly without parsing the code (just tokenizing it) if you have indentation to help you.

I originally posted the comparison article to a mailing list of my own; would you mind if I forwarded this conversation about it to the list too?

Subject: Re: python indent sensitive
Date: Wed, 19 Jun 2002 15:54:08 -0700
From: "Simon J. Gerraty" <[email protected]>
> > Further, while indentation alone may suffice for a screen's worth of
> > code, I find it inadequate for grossly large blocks of code.
> 
> Meaning that you need both block structure and editor support for it?
Not sure I follow.
> > Note that I often have to debug programs written by others so the
> > fact that a huge function should be re-organized is orthogonal to
> > understanding what it is doing.  Being able to ask a tool like an
> > editor "go show me where this block started" is very handy.
> > Matching braces etc makes this easy.
> 
> Well, unfortunately forward-sexp and backward-sexp don't think Python
> blocks are sexps, but when I want to know where a block began, I

I guess that's my point. A little ginger bread like braces would make python look a bit more like other langs that emacs groks well.

> I originally posted the comparison article to a mailing list of my
> own; would you mind if I forwarded this conversation about it to the
> list too?

Sure, no problem.

--sjg

-- <[email protected]> Kragen Sitaker <http://www.pobox.com/~kragen/>

A good conversation and even lengthy and heated conversations are probably some of the most important pointful things I can think of. They are the antithesis of pointlessness!

-- Matt O'Connor <[email protected]>

Braces Problem

A really useful tool (written in Python or Perl or awk or whatever) would read in a "Braced Python" file, remove the {}'s and redo the indentation inside them, and then write out a syntactically-correct file. such a tool comes with the standard python distribution (look for pindent in the Tools directory).
Re:Python - so close... (Score:2, Insightful)
by JohnPM on Sunday April 23, @12:48PM EST (#84) (User Info)
The syntactic indenting in Python is actually extremely cool. Ok, so maybe it means that emacs is the only editor it makes sense programming with - but we knew that already right? The main benifit I see to syntactic indenting is that is narrows down the possible range of coding styles. If you think about it, most of the (dare I say) splintering of C/C++/Java coding styles is due to the placement of the { and } symbols. This acts against readability for other developers. It's also less typing.

If you like the keybindings and programmability of Emacs, but don't like its size, try JED which also has a pretty good Python mode, too.

...and yet grounded in its 1950's roots?? Idea! (Score:3, Interesting)
by devphil on Sunday April 23, @12:35PM EST (#79) (User Info)
That's something that seriously bugs me about Python. I have tried over the years to not be a syntax bigot, but Perl loses in this respect. I saw the quip, "Perl -- the only programming language that looks the same both before and after RSA encryption," and it makes perfect sense.

Dilbert's joke about a rat dancing on his keyboard and writing a web browser could probably come true in Perl.

Python is a big, big win. But the required indentation just stupifies me. I feel like I'm writing a FORTRAN 77 program, indenting to the correct place so that the compiler/interpreter can find the right column of the punched card...

I'm not a big fan of 1950's cars, clothes, music, or programming languages.

A really useful tool (written in Python or Perl or awk or whatever) would read in a "Braced Python" file, remove the {}'s and redo the indentation inside them, and then write out a syntactically-correct file. (For bonus points, play some 50's tunes while it's converting.)

This would aid the transition from free-form languages like C++ (and FORTRAN 95...). It's enough to introduce new ideas; don't beat the user over the head with personal indentation preferences at the same time.

Re:...and yet grounded in its 1950's roots?? Idea! (Score:4, Insightful)
by eff on Sunday April 23, @01:21PM EST (#88) (User Info) http://www.pythonware.com/people/fredrik
A really useful tool (written in Python or Perl or awk or whatever) would read in a "Braced Python" file, remove the {}'s and redo the indentation inside them, and then write out a syntactically-correct file.

such a tool comes with the standard python distribution (look for pindent in the Tools directory).

(there's also something called corbascript, which is pretty much python with braces...)

real python programmers tend to use python-aware editors, but that's another story...

Re:Python - so close... (Score:1)
by mcdonc ([email protected]) on Sunday April 23, @11:53PM EST (#122)
(User Info) http://www.digicool.com
That's completely false. Perl certainly has strong OO syntax. Perl, in fact, has much stronger OO than Python. A couple of reasons are that in Perl you have privacy, and also because in Perl its much easier to generate metaclasses.

I write python all day long every day. I used to do same for perl. This statement is pretty darn funny. As my coworker jeffrey (with a derisive snort) would say "OO is all about virtual private methods and late bindings" (then bust up laughing).

Re:Python....watch out...(maybe) (Score:2, Informative)
by TresEquis on Sunday April 23, @09:33PM EST (#117)
(User Info) http://www.palladion.com

From what I can tell, they plan on revamping pretty much all of the syntax...and it won't be backwards compatible in the end release.(they do plan on working slowly up to it, AFIAK)

Nyet, tovarisch. The "backwards compatibility" issue in Python 3000 is mostly likely to bite extension writers, who code to Python's C API; most code written in Python will see very little, if any, compatibility problems.

I don't recall any of the specifics, but maybe they will be integrating the most sought after change....no more tabs and whitespace! ;)

No way, no how, not ever! The use of indentation to indicate block structure is a core feature, there by explicit design, to increase readability (you probably indent your C/C++, Java, or Perl to match the block structure already, right? so just lose the "noise" characters, and let the parser read the indentation). The issue has been repeatedly raised on comp.lang.python, mostly by people who haven't actually used Python for anything significant. As for the dreaded whitespace-eating nanoviruses, those have been discussed extensively on the newsgroup, as well.

Re:Python....watch out...(maybe) (Score:1)
by soulhuntre on Monday April 24, @12:49AM EST (#127)
(User Info) http://www.virtualchemy.com
"...so just lose the "noise" characters..."

Sorry, but no. This is simply too much for a number of reasons...

  1. positionally dependant languages are simply silly.
  2. my programmers work in perl and C++ as well, there is no reason to inflict a radically different syntax system on them
  3. for those of us with long programming histories, those {} characters are important visual cues in the code we read, I have no intention of turning off reflexes I learned over the last 20 years or so just to satisfy someones syntax egotism.

Ken

Re:Python....watch out...(maybe) (Score:1)
by CoderDevo on Monday April 24, @04:57AM EST (#130)
(User Info)
Your argument falls apart when you realize that Python is designed to be a language that is for newbies, is for oldies, is here to stay and will create careers for Python programmers.

Answers:

1) positionally dependant languages are simply silly.

No paradigm is "simply silly." It either works, or it doesn't. In the context of Python, positional dependence helps define the language. Have you ever taken over someone elses code? This enforces easy to read, easy to maintain code.

2) my programmers work in perl and C++ as well, there is no reason to inflict a radically different syntax system on them

Not much faith in your programmers. I see that if they know Perl well, then there may be no need to use Python. However, I was given the choice of learning a modern scripting language. I already knew Borne shell and awk. After much research, I decided on Python. My C++ is strong and Python was an obvious fit for my skills and style. I am still happy with the decision.

3) for those of us with long programming histories, those {} characters are important visual cues in the code we read, I have no intention of turning off reflexes I learned over the last 20 years or so just to satisfy someones syntax egotism.

These "visual cues" are learned. Just as positional dependence is learned. It's just a different paradigm, not necessarily better or worse.(better) :)

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

In praise of mandatory indentation for novice programmers programming



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: September, 28, 2019