Python indentation

C

Christopher T King

Because TAB is TAB and not 8 * SPACE nor 4 * SPACE nor 2 * SPACE. In
editor you don't see a TAB, you see 8 * SPACE or 4 * SPACE or 2 * SPACE
or any number of spaces you set in your editor options. There's no

Which is exactly why I use tabs -- if I don't like the indentation width,
I just change and option and BAM! it's changed! Whereas with spaces, I'm
stuck with looking at one- or eight- character indents, rather than my
preferred tab width setting.

My other reason for using tabs is that my preferred editor (JOE)
couldn't unindent space-based indents prior to its 3.0 release (very
recent). Now my excuse is WHAT IF I HAVE TO USE NOTEPAD?!?! :)
 
U

Ubergeek

Mike said:
Nope. People have been telling me to use spaces in my Python for
*years*, and I'm nowhere near assimilated. The number of silly
occasions where hitting <del> or <backspace> to remove a tab works where
the editor doesn't pick up an attempt to remove 4-or-so-spaces keeps me
going back to the simple "a tab is an indent" approach. The simple fact
( ;) I know, it's a holy war, there are no facts, but I feel like
tweaking the spacies) is that having 3 or 4 or 2 or 8 characters
represent the concept "indentation level" is just silly when you've got
the single character representation available.

IMHO, it doesn't make that much difference if you use all tabs or you
use all spaces for your indentation if you're the only one that ever
edits the source file. The problem comes in if the two ever get mixed
in the same file, which is particularly problematic if you have more
than one person working on a file or if you share some code as open source.

If you use tabs in your source with a 4-space width and I make a mod to
one of your files when I have my editor configured to insert 4 spaces
for indent, it'll look the same on the screen but Python will get very
unhappy. Because all blocking in Python is based on lines with
identical amounts of indentation, Python has to convert all those tabs
to some amount of spaces in order to calculate indentation. Since
Python has no idea what tab width you have set in your editor, it has to
assume a fixed size for tabs (which, IIRC, is 8 spaces). Because of
this, your 4-space wide tab and my 4 real spaces represent different
indentation levels and the blocking of the code is now hosed.

The advantage of using all spaces is that no matter what editor you load
a source file in or what your tab-width configuration is, it is
guaranteed that a human being and the Python interpreter will both see
the indentation the same way.
 
P

Peter Hansen

Steve said:
What Istvan is using is better known, to me at least, as "the vi
argument". IE, it was best for people to learn vi over another editor because
one could be stuck with nothing but vi to do editing with since all unixes
came with vi stock. Whatever would someone do if they were incapable of using
their preferred editor and stuck *only* with vi!?

Nevermind that there are now several well used flavors of unix which do
not come stock with vi or, at the very least, only vi. And some of the
situations that the people would create. "What if you only had a laptop, an
install disc for intel solaris and were stuck on a stranded isle with no
network access to get anything else!? You really need to conserve battery
power so you can't waste time learning vi then but you need it to write the
perfect program to calculate the best method of communication using firewood.
YOU DON'T KNOW VI!!! WHAT WOULD YOU DO!!!!! AIYEEEEEE!!!!" Ok, I may be
exagerrating a tiny bit but only a tiny bit.

I'm actually pretty inept with vi (or vim), to the point that I don't
actually know how to configure it for use with Python. And every
now and then, I'm forced to use it. When that happens, I find
that writing my little one-off (since inevitably that's what it
is, even if it's to figure out how to use smoke signals on a
desert island) is best done with single spaces. Bingo-bango, no
typing disadvantage over TABs... even better, I get to use
my *thumb*, which is much stronger than my middle finger, and
don't need to move my wrist at all, decreasing the effect of the
whole process on my carpal tunnel syndrome.

Basically, the "vi argument" has no merit, since the only times
one can't get access to a decent editor, preconfigured to do the
Right Thing with Python, is an emergency, and in an emergency,
single spaces work as well as tabs. End of argument. :) (No,
really, that will stop the discussion permanently. Really!)

-Peter
 
S

Steve Lamb

The style I use writes it as:

if (condition) {
doThis();
doThat();
} else {
doWhatever();
andSoOn();
}
which is 7 lines, only 1 more than the Python version.
But this does demonstrate an advantage of Python: No arguments over
where to put braces :)

Damn skippy. 'round these parts it would look like this:

if (condition) {
doThis();
doThat();
}
else {
doWhatever();
andSoOn();
}

8 lines. But that's because I never understood why anyone would
willingly use the '} else {' construct since the else is ovten obscured.
Keyword opens the block, } ends the block, never put a block open and close on
the same line.
 
S

Steve Lamb

Is there a reason why a TAB is not a TAB is not a TAB?

Yes. Name the number of spaces a TAB should translate into.

That was easy. Now explain why your answer is right and the next guy's
answer, which is different than yours, is wrong.

Oh, not so easy, eh? TAB, by it's very nature, is a variable and
configurable width. A SPACE is not.
Is it really that trivial to set up an editor so that when one hits
delete/backspace to 'un-align' a line of code it deletes as
many space characters as the soft-tab has inserted?
I don't think so.

Uhm, yes, it is. With vim part of my configuration when loading Python
files:
au FileType python set autoindent smartindent et sts=4 sw=4 tw=80 fo=croq

Translates into:

Autoindent on
Smartindent on
Expandtab on
SoftTabStop 4 spaces
ShiftWidth 4 spaces
TextWidth 80 spaces
FormatOptions
c - auto-wrap comments, automatically inserting current comment character
r - Automatically insert current comment character after hitting enter in
in insert mode
o - Automatically insert current comment character after hitting o or O in
command mode.
q - allow formatting of comments with gq (IE, reflow and keep comment
characters at the front of the line).

Where's the magic? Here:

-----
'softtabstop' 'sts' number (default 0)
local to buffer
{not in Vi}
Number of spaces that a <Tab> counts for while performing editing
operations, like inserting a <Tab> or using <BS>. It "feels" like
<Tab>s are being inserted, while in fact a mix of spaces and <Tab>s is
used. This is useful to keep the 'ts' setting at its standard value
of 8, while being able to edit like it is set to 'sts'. However,
commands like "x" still work on the actual characters.
When 'sts' is zero, this feature is off.
-----

Number of spaces that a <Tab> counts for while performing editing
operations like....<BS> (Backspace). IE, I set STS to 4. I hit tab, 4 spaces
are inserted. I hit backspace, 4 spaces are removed. It's just that simple.

As for alignment operations ShiftWidth is used for << and >> which are
used to (de)indent blocks of code.
 
P

Peter Hansen

Christopher said:
My other reason for using tabs is that my preferred editor (JOE)
couldn't unindent space-based indents prior to its 3.0 release (very
recent). Now my excuse is WHAT IF I HAVE TO USE NOTEPAD?!?! :)

On what planet is *anyone* forced to use Notepad for real
development? That is, for anything other than emergency
one-offs?

-Peter
 
S

Steve Lamb

My other reason for using tabs is that my preferred editor (JOE)
couldn't unindent space-based indents prior to its 3.0 release (very
recent). Now my excuse is WHAT IF I HAVE TO USE NOTEPAD?!?! :)

You slit your wrists with a ceremonial butter knife?
 
D

David Bolen

Steve Lamb said:
8 lines. But that's because I never understood why anyone would
willingly use the '} else {' construct since the else is ovten
obscured. Keyword opens the block, } ends the block, never put a
block open and close on the same line.

Oh, I thought I wouldn't contribute to this thread, but what the hey...

I certainly willingly use the "} else {" construct - probably to me
because it stands out quite well and doesn't add additional noise
along the left edge (the } and else on separate lines feels jarring to
my eyes). There's plenty of density in the "} else {" (as opposed to
a simple closing brace) to draw my eye.

Clearly it's an "in the eye of the beholder" thing. I will admit to
being a K&R "one true brace style" guy. Maybe from having learned C
with K&R, but possibly a subconcious effort to minimize my brace
impact (minimize wasted empty brace only lines and impact on the
visual blocks I was creating) on what was otherwise an indentation
based block format I was trying to express. Little did I know I
really just wanted Python :)

Interestingly, I never even really considered the else and next
opening brace ("else {") on its own line as an option - the folks that
I've seen use else starting on its own line also tend to be those that
prefer the Allman/BSD style of braces, in which case else would be
alone on the line with the closing and opening braces on their own
lines above and below it. I don't mind BSD style, but it does eat up
a lot of extra lines that only have braces on them, which cuts down on
the density of code you can view easily on a single screen.

Then again, I also see and feel similarity between my formatting of C
in:

if (stuff) {
do something
} else {
do something else
}

and my Python:

if stuff:
do something
else:
do something else

is in terms of indentation and line position of portions of the flow
control. The only brace in the C code that unnecessarily adds lines
is the final closing one. Of course I'm sure the same argument could
be worded about the other popular formats. To each his own :)

-- David
 
G

Gary Herron

Jacek Generowicz a écrit :

It's this way because we (the Python community) feel VERY strongly
that this is the correct way to do it.

In any program in any language, one must maintain correct indentation
to make the program structure human-readable. (If you don't, you
should be fired immediately because no one, yourself included, will
ever be able to read your code.) Given that, why should any language
force us to maintain a second compiler readable method ("{" and "}" or
whatever) for specifying the program structure.

Having only one method of specifying program structure (and one which
is readable by both human and the compiler) makes sense. Indeed, many
of us have gotten to the point of believing that all those other
languages are simply WRONG and only Python has it CORRECT.

May you enjoy Python enough to get to the same level of understanding,
Gary Herron
 
L

Leif K-Brooks

bruno said:
The fact is that there is no brace-and-indent-style-war with Python !-)

Seems to me like we're having one in this thread right now, even though
it's about a different family of languages.
 
G

Grant Edwards

Seems to me like we're having one in this thread right now, even though
it's about a different family of languages.

That just goes to show you how great Python is. We have to
talk about other languages to have a good argument.
 
S

Sateesh

If you are used to coding in vi editor, it supports C (or for that matter
any language that uses braces) well. I feel the biggest advantage of using
braces is that I can know the start and end of the block of code, and this
becomes important if the code block is big and does not fit your screen. All
I need to do is to place the cursor on the { or } and press the key
combination shift+%. This will show the start and the end brace for that
block. And if there is an error, you will clearly know that using this key
combination. I have been using this method all the time, and it proved to be
really effective.
I am just wondering, how huge if, else blocks of code can be easily handled
in python. Is it not so anyone reading python code written by someone else
will get lost to find the start and end of these if, else blocks, or for
that matter any looping constructs.

Cheers!
Sateesh
 
J

Jacek Generowicz

Steve Lamb said:
What Istvan is using is better known, to me at least, as "the vi
argument". IE, it was best for people to learn vi over another
editor because one could be stuck with nothing but vi to do editing
with since all unixes came with vi stock. Whatever would someone do
if they were incapable of using their preferred editor and stuck
*only* with vi!?

Nonononononoooooo! You've got it all horribly wrong: _ed_ is the
standard text editor.

http://www.gnu.org/fun/jokes/ed.msg.html
 
J

Jacek Generowicz

Istvan Albert said:
Is it really that trivial to set up an editor so that when one hits
delete/backspace to 'un-align' a line of code it deletes as
many space characters as the soft-tab has inserted?

Yes. I do _exatly nothing_ to my editor to configure it to do this :)

You can't get more trivial than that.
 
S

Sam Jervis

On what planet is *anyone* forced to use Notepad for real
development? That is, for anything other than emergency
one-offs?

-Peter

The company where I used to work was one such planet :(

Nonetheless, tabs are still evil even if you are forced to use notepad.
I used a two space indent, which was tolerable for the ASP work I was
doing.

<OT>
The problem was that they didn't want to spend money getting a license
for any of the IDEs used by the permanent staff for me because I wasn't
there for long, and I wasn't allowed to install my own editor because
they had a general policy against installing anything "unapproved" on
their computers. Vim fell under this category and I was told to remove
it before "anyone saw it".

This was before the all singing all dancing notepad you get with Windows
XP. This was a notepad which didn't have a line number display in the
status bar or a go to line feature. I used to locate errors by putting
a 6 at the start of the line that I thought was wrong and seeing which
line the resulting ASP syntax error was on.
</OT>

Sam
 
A

Antoon Pardon

Op 2004-07-07 said:
I'm not sure why this is relevant.


Which is why I asked you to name a desirable code construction that
Python denies you due to it's indentation rules. If, for example, you
find the following style compelling:

Well personnaly if i have a loop with the terminating condition
in the middle I now have to write it like this

while True:
code
if condition: break
code


I would prefer to indent sucu code as follows:

while True:
code
if condition: break
code


Why? because the loopbreaker is IME part of the loopstructure,
not an ordinary if statement in the loopbody.

This is why I prefer free form languages. If you need certain
control structure that is not directly in the language but
can be simulated, you can still indent your code according
to the structure you have in mind as opposed to the structure
that is forced upon you by the simulation.
 
A

Antoon Pardon

Op 2004-07-07 said:
That is what I wrote about. In the beginning, you think of the
indentation as a restriction. Later, you will be glad about it, and you
will not desire to structure your code otherwise.

My experience is otherwise.
 
A

Alan Gauld

Clearly it's an "in the eye of the beholder" thing. I will admit to
being a K&R "one true brace style" guy.

Actually its not just an "eye of the beholder thing". McConnell
discusses this in his Code Complete book and cites studies that
showed that the style that most programmers preferred was not the
style that led to best comprehension.

As a result of that I changed my C style from

if (foo)
{
doit()
}
else
{
doAnother()
}

Which had been the preferred style in McConnels reference study
To

if (foo) {
doit()
}
else {
doAnother()
}

Then I changed my "style" even more radically to:

if foo:
do it()
else:
doAnother

Both of which matched McConnels best practice, but the Python one
gave me no cosmetics versus comprehension debate... :)

Alan G.

Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
 
A

Alan Gauld

I am just wondering, how huge if, else blocks of code can be easily handled
in python.

Given that modern editors typically display 50-100 lines of code
at a time its not been a big problem. Also given the much higher
level of code in Python vv C you don't get so many huge blocks.
Finally if you regularly come across blocks of code more than 50
lines long then I think its probably time to start refactoring
that code! :)

In fact the longest indented blocks I find are class definitions.
Those can be several hundred lines long and it can be hard to
know which class you are reading if several big classes exist
inside a module. It's one area where I wish Python had adopted
the Delphi interface/implementation style where the class
interface isb published and the individuial methods are
implemented separately

class C
def __Init__(a,b,c): pass
def f(d): pass
def g(): pass

implementation: <---- New keyword or something?

def C.__Init__(a,b,c)
# initialise here

def C.f()
# real code here

def C.g():
# and here

But thats for another topic I guess... :)


Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
 
V

Ville Vainio

Antoon> I would prefer to indent sucu code as follows:

Antoon> while True:
Antoon> code
Antoon> if condition: break
Antoon> code


Antoon> Why? because the loopbreaker is IME part of the
Antoon> loopstructure, not an ordinary if statement in the
Antoon> loopbody.

It's still going against the underlying block structure, so a source
code "prettifier" would screw it up even if Python allowed it.

BTW, every time this indentation issue comes up I'd like to point
people to pindent.py in Tools/scripts directory. It augments source
with block closing comment (and vice versa), like this:

def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar

The script is either in:

Python23/Tools/Scripts/pindent.py (DOS)
/usr/share/doc/python2.3/examples/Tools/scripts/pindent.py (Debian)

Antoon> This is why I prefer free form languages. If you need
Antoon> certain control structure that is not directly in the
Antoon> language but can be simulated, you can still indent your
Antoon> code according to the structure you have in mind as
Antoon> opposed to the structure that is forced upon you by the
Antoon> simulation.

You realize that this approach is slightly heretical, do you?
Indentation should follow the "real" block structure *exactly*,
anything else is an error that confuses the reader.

The while 1 - break structure doesn't even need extra clarification,
because the break is typically in a very idiomatic place - right after
the assignment in the beginning, or at the very end if it's
semantically a repeat-until loop (which are rare).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top