Is it good - perhaps because it saves space and eliminates keypresses?
Or is it bad - perhaps because it makes program flow dependent on
invisible, and unpronouncable characters - and results in more
manual alignment issues by preventing code formatters from managing
indentation?
Python is certainly pretty unorthodox in this area.
How would you have dealt with the issue of how to group statements?
--
__________
|im |yler http://timtyler.org/ t...@tt1lock.org Remove lock to reply.
> What do you guys think about Python's grouping of code via indentation?
This is a Python newsgroup. Assume that we all have been brainwashed.
> How would you have dealt with the issue of how to group statements?
Off the top of my head I can think of one other way: associate a wav file
with every grouping level and have your editor play it while you are
editing that particular level.
I think that would be very effective to get a Pythonista acknowledge the
merits of C/Pascal grouping markers -- noisy, but not *that* noisy...
Peter
Peter> This is a Python newsgroup. Assume that we all have been
Peter> brainwashed.
+1 QOTW.
Skip
I think it was a mistake, but I'm probably in the minority here.
--
Antoon Pardon
Um, why?
I think it isn't quite what's needed, based on the observation that it makes
shifting from expression to statement context difficult enough that useful
features
like blocks don't have a decent syntax.
On the other hand, it saves me an awful lot of hassle; it's one less thing
to have to get into my head.
John Roth
>
> --
> Antoon Pardon
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Love it or leave it...
Kent
It's good, but this is only a minor reason.
The reason this is good is because it exactly reflects the way human
beings mentally group code in their heads. In Python, you can eyeball
grouping with 100% accuracy (except for one flaw that's being phased
out). Not so with other languages. In other languages, you have two
simultaneous ways of grouping code: the way that makes sense to humans
(indentation), and the way (braces or begin/end). This creates the
possibility of mismatch, and it puts an extra burden on the programmer
to make sure computer and human grouping stays synchronized.
Grouping by indentations also goes a long way to prevent sloppiness.
No matter how sloppy your style is, you can't slop away the way the way
program was nested in Python; thus a reader should be able to follow
the flow of just about any code. I've ended up as the computer expert
at my engineering firm, so I get (non-Python) code to debug from time
to time, and I can attest that inconsistent style is the single worst
thing that everyone does to make code unreadable. Python-like
indentation would instantly halve that problem.
The drawbacks are insanely minor. It makes one liners more difficult,
and can result in transmission difficulties with some stupid programs
that helpfully strip leading whitespace. (There's another drawback in
Python that isn't inherent to grouping by indentation, namely the
possibility of mixing spaces and tabs. This is the flaw that's being
phased out.)
> Or is it bad - perhaps because it makes program flow dependent on
> invisible,
It doesn't. I suspect Pythonistas will heavily attest to that. But,
as I said, it does make it virtually impossible for sloppy code to
mislead you about the flow. Overall, if someone hands you a random
piece of C code, and a random piece of Python code, you will be more
likely to easily follow the flow of the Python.
> and unpronouncable characters - and results in more
> manual alignment issues by preventing code formatters from managing
> indentation?
This is true. Most common complaint is changing the nesting level of a
block of code. Good editors have ways to cope with this, just as good
editors have ways to cope with all these superfluous braces in other
languages.
> Python is certainly pretty unorthodox in this area.
>
> How would you have dealt with the issue of how to group statements?
Having experienced Python, I can say pretty earnestly that, were I
designing my own language, there is no other way I would do it.
Grouping by indentation is a slam dunk for me.
--
CARL BANKS
1) It makes it hard to see how many levels are dedented at the end of
a suite, and sometime makes it difficult to see where the end
of a suite is. If e.g. you are looking at the code spread over
two pieces of paper, it is sometimes hard to see whether the
suite ends at the end of the first page or not.
2) It makes it hard to introduce some kind of new syntax constructs.
Sometimes its isn't clear what would be the best indentation scheme
for a syntantical structure, or some usefull syntantical won't fall
in the indentation scheme that python provides. I think it a
shame that these consideration would limit what constructs
get into python or not.
3) Sometimes the structure of the algorithm is not the structure
of the code as written, people who prefer that the indentation
reflects the structure of the algorithm instead of the structure
of the code, are forced to indent wrongly.
--
Antoon Pardon
You might read Eric Raymond's Why Python? article
[http://www.linuxjournal.com/article/3882]
I would agree with him in that it just seems natural.
That is not true. You can with the innermost levels, but it isn't
always that clear with intermediate levels.
> Not so with other languages. In other languages, you have two
> simultaneous ways of grouping code: the way that makes sense to humans
> (indentation), and the way (braces or begin/end). This creates the
> possibility of mismatch, and it puts an extra burden on the programmer
> to make sure computer and human grouping stays synchronized.
Structure/Disciplined programming is a burden in general. I have
never found putting braces or what ever delimiter such a problem.
I don't see people argueing that putting the right number of parenthesis
and or brackets is an extra burden.
> Grouping by indentations also goes a long way to prevent sloppiness.
> No matter how sloppy your style is, you can't slop away the way the way
> program was nested in Python; thus a reader should be able to follow
> the flow of just about any code.
IMO the flow of a lot of code would be easier to follow if code
like "if condition: break" could be dedented, because such a
condition is really at the same level as the "while"
> I've ended up as the computer expert
> at my engineering firm, so I get (non-Python) code to debug from time
> to time, and I can attest that inconsistent style is the single worst
> thing that everyone does to make code unreadable. Python-like
> indentation would instantly halve that problem.
Use a tool for that. If people want something in python that python
doesn't has, those people are refered to tools that provide it.
It it works in that direction, it should also work in the other
direction and people that would like some feature of python in
an other language should use a tool for that. You wnat consistent
style? Use a tool to put all your source in a consistent style.
> The drawbacks are insanely minor. It makes one liners more difficult,
> and can result in transmission difficulties with some stupid programs
> that helpfully strip leading whitespace. (There's another drawback in
> Python that isn't inherent to grouping by indentation, namely the
> possibility of mixing spaces and tabs. This is the flaw that's being
> phased out.)
>
>
>> Or is it bad - perhaps because it makes program flow dependent on
>> invisible,
>
> It doesn't. I suspect Pythonistas will heavily attest to that. But,
> as I said, it does make it virtually impossible for sloppy code to
> mislead you about the flow. Overall, if someone hands you a random
> piece of C code, and a random piece of Python code, you will be more
> likely to easily follow the flow of the Python.
Not with my own code. The difference is not great but my C programs
have a slight edge here.
>> How would you have dealt with the issue of how to group statements?
>
> Having experienced Python, I can say pretty earnestly that, were I
> designing my own language, there is no other way I would do it.
> Grouping by indentation is a slam dunk for me.
Well to each his own.
--
Antoon Pardon
Oh, not the right number. But I have seen wars waging over the correct
indention style to use. Braces behind flow control statements, or beneath,
and if the latter, indented halfways or not?
> Use a tool for that. If people want something in python that python
> doesn't has, those people are refered to tools that provide it.
> It it works in that direction, it should also work in the other
> direction and people that would like some feature of python in
> an other language should use a tool for that. You wnat consistent
> style? Use a tool to put all your source in a consistent style.
And what to do if two (or more) people can't decide on what convention to
use? And just in case you never worked with CVS: Having mutually commits of
sourcecode that has been subject to code formatting tools often creates a
hellhole of conflicts - which is a major PITA.
> Well to each his own.
Amen. Why don't you use ruby? It has braces. And code blocks. And its more
liberal towards overriding builtins, which might appeal to you.
--
Regards,
Diez B. Roggisch
Normally one is the project leader. He decides.
> And just in case you never worked with CVS: Having mutually commits of
> sourcecode that has been subject to code formatting tools often creates a
> hellhole of conflicts - which is a major PITA.
>
>> Well to each his own.
>
> Amen. Why don't you use ruby? It has braces. And code blocks. And its more
> liberal towards overriding builtins, which might appeal to you.
I have other problems with it. I have problems with all languages
currently available, so I use those which rub me wrong the least.
I think the indentation syntax of python was a mistake, but for
the most part it is a minor issue and it doesn't weight heavy enough
to go and use an other language, although I keeping looking at
the other languages.
--
Antoon Pardon
Whishful thinking.
Another problem I have with code that is _not_ layouted the way I'm used to
it is that the perception of what very code does gets more difficult to me.
You seem to have the same troubles, I take that from your desire to reflect
algorithmic structure different from syntactic. And I guess most people
havo, otherwise the whose layout-thing wouldn't stir up so bad feelings all
the time.
And as not all code I read is code I'm supposed to write (might it be OSS
that I dig into for debugging, or other 3rd party sources I can't control,
e.g. different departments with different project leaders) I found that
python's way of imposing a rather strict layout on _all_ coders out there
means I've less trouble digging into other peoples code. Which is useful -
and it seems that I'm not the only one with this feeling.
Secondly, Python "nudges" me into writing better
(easier to maintain and clearer to understand) code by
influencing me towards splitting my code into smaller
functions/classes. If I find myself with more than 3-4
levels of indentation, I probably need to move some of the
lower level code into a function or a class anyway (I
actually ran into this this very morning). Some might
interpret this as a negative, I don't. I find that a lot
of programmers put WAY too much code into single individual
modules (main programs, functions) for their own good. It
is harder to read, harder to understand, and harder to
maintain. I believe that Python tends to make these
programmers better by influencing them to write more
modular code. The best method for deeply nested grouping
is usually the introduction of functions/classes that
divide the deeply nested grouping into more manageable
and debuggable pieces.
Larry Bates
Larry Bates wrote:
>
> Secondly, Python "nudges" me into writing better
> (easier to maintain and clearer to understand) code by
> influencing me towards splitting my code into smaller
> functions/classes. If I find myself with more than 3-4
> levels of indentation, I probably need to move some of the
> lower level code into a function or a class anyway (I
> actually ran into this this very morning). Some might
> interpret this as a negative, I don't. I find that a lot
> of programmers put WAY too much code into single individual
> modules (main programs, functions) for their own good.
Agreed. Any method where you have to scroll to figure out what matches
what is _too big_. This principle holds true for any language. Keeping
to that aesthetic forces you to modularize your code and often generates
far more flexible functions/methods than you would have any right to
expect otherwise.
As far as grouping by indentation goes, it's why I fell in love with
Python in the first place. Braces and so on are just extraneous cruft
as far as I'm concerned. It's the difference between Vietnamese verbs
and Latin verbs;-)
Metta,
Ivan
----------------------------------------------
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours
I think the operational definition of a "zealot" is someone who thinks
what they have is absolutely perfect, and refuses to examine the
alternatives.
Not a very inspiring slogan though:
"Python - the least of 1,000+ evils."
> 1) It makes it hard to see how many levels are dedented at the end of
> a suite, and sometime makes it difficult to see where the end
> of a suite is. If e.g. you are looking at the code spread over
> two pieces of paper, it is sometimes hard to see whether the
> suite ends at the end of the first page or not.
One can use appropriately indented comment lines instead of closing
brackets for this purpose.
> 2) It makes it hard to introduce some kind of new syntax constructs.
I consider this as much a plus as a minus ;-)
> 3) Sometimes the structure of the algorithm is not the structure
> of the code as written, people who prefer that the indentation
> reflects the structure of the algorithm instead of the structure
> of the code, are forced to indent wrongly.
Do you have any simple examples in mind?
Terry J. Reedy
A major plus. I was fanatic about carefully indenting my C code.
> Is it good - perhaps because it saves space and eliminates keypresses?
It eliminates redundancy.
Terry J. Reedy
Say I buy into the indentation ideology. Python then has this inconsistency: :
Why do we need : at the end of our if and for loops? I spend approximately 6
minutes/100 lines of code going back and finding all of the times I missed :.
Is it for cheating?
if False: print ":"
Now, what happened to the whitespace idea here? This code seems very
unpythonic. I think : is great for slices and lamda where things go on one
line, but to require it to specify the start of a block of code seems a
little perlish.
--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
During the usability studies for the language ABC, which Guido worked on
before developing Python and also used indentation for grouping, it was
found that the colon improved readability.
I don't know what those studies said about the frequency of people
forgetting to put in the colon. Anecdotally, I can say that I do it very
rarely.
--
Robert Kern
rk...@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
I can't remember having ever done it, although I am sure I have. The
real question is, though, 6 minutes per 100 lines of code? There
probably aren't more than 30 lines out of those 100 that should end in
a colon. Assuming you forget half your colons, you're spending upwards
of 20 seconds per colon?
If you want, I'll write a script that checks for colons at the end of
lines before increased indentation, and asks you if you want to put
one there - I could save you 5.8 minutes per 100 lines of code. How's
that for a productivity boost?
Peace
Bill Mill
bill.mill at gmail.com
As for the one-liner you mentioned, you may call it
cheating, but it is consistent with other languages
that allow single-line blocks this freedom and I don't
have a problem with "you can put one line after the colon
but not more than one" rule.
Larry Bates
It is just as inconsistent as putting a colon after inconsistency in
the above line.
I've always viewed it as analogous to english grammar -
Go to the store and buy the following:
Milk
Eggs
Spam
If there is a sale on beer:
Buy Heineken
otherwise:
Buy Budweiser
The colon terminates the directive and then the objects are indented.
It depends. Are you looking to eliminate punctuation entirely, or strike a
proper balance?
Yes, it's a loaded question, but yes, it reflects reality.
Go look at a few hundred lines of Python code. Strip the colons off of the
end. Barring the
if bleh: something()
one-liners*, it starts to look like a giant run on sentence to me.
That's the native English speaker in me, but still, the historic trend was
to add some punctuation as soon as technology made it non-burdensome. You
don't *need* vowels in written text, either, but I see you and your
language using them.
Readability counts.
... practicality beats purity.
Dropping the colon would just be getting silly.
*: Where the colon *is* necessary; you need *something* to
delimit the condition from the action, we've discussed this in the past
but here's an example:
if (a)(b)(c)
can be
if (a):(b)(c)
if (a)(b):(c)
)
-- Paul
BTW - anyone who tries to justify code design based on "eliminating
keypresses," or, my God!, "saving space" has no earthly clue about
where the mental energy goes in code development, or code maintenance
(which is where 5-10X the development costs are spent).
Or, paraphrasing Mark Twain, "Python is the worst possible programming
language, except for all the others."
--
- Tim Roberts, ti...@probo.com
Providenza & Boekelheide, Inc.
I particularly hate it, but Python has lots of good
things which compesate that (another annoying point
of Python are slices -- mine are always off by 1).
I always write explicitly ends as #end, so that I
can reorganice the code easily if necessary. Maybe
in the future, when Ruby matures, I could change
my mind, but currently Python is still my favourite
scripting language (as formerly was Tcl).
Javier
___________________________________________________________
Javier Bezos | TeX y tipografÃa
jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos
............................|...............................
CervanTeX (Spanish TUG) | http://www.cervantex.org
I've been trying to establish that a while ago, but would attribute it to
Winston Churchill -- so I'm a little confused now. Can you provide the text
where it's taken from?
Peter
PS: Perhaps we can settle on (with apologies to Groucho Marx): I wouldn't
want to program in a language I can actually understand.
A little Googling shows it is widely attributed to Churchill but I didn't find an original source.
The full quote seems to be "democracy is the worst possible form of government except - all the
others that have been tried".
The most authoritative citation I can find is from this page at The Churchill Centre:
http://www.winstonchurchill.org/i4a/pages/index.cfm?pageid=591
Interestingly, this quote is not on their page of famous quotes:
http://www.winstonchurchill.org/i4a/pages/index.cfm?pageid=388
Kent
Peter> I've been trying to establish that a while ago, but would
Peter> attribute it to Winston Churchill -- so I'm a little confused
Peter> now.
Google thinks it's Winston Churchill as well. I did come across a quote
wiki:
None of the quotes attributes to Mark Twain looked like the democracy quote,
though he had a few other good ones related to goverment and politics that
might be worth a passing glance:
http://en.wikiquote.org/wiki/Mark_Twain
Skip
> > What do you guys think about Python's grouping of code via indentation?
>
> This is a Python newsgroup. Assume that we all have been brainwashed.
;-)
I had a good look for comp.lang.python.advocacy before posting my
question - and coated my shield with a fresh dose of flame repellant.
While the question does have a trollish character - and I can
easily imagine I'm not the first to ask it and that participants
may be sick of hearing about the issue - I was sincere in wanting
to know the answer. Fortunately, I do seem to have elicited some
intelligent responses - thanks very much to everyone who answered.
FWIW, my initial impression was "yuck". After considering the issue,
I could see quite a few advantages. At the moment, while rather torn
on the whole issue, I seem to be heading back in the direction of my
first impressions.
> > What do you guys think about Python's grouping of code via indentation?
> >
> > Is it good - perhaps because it saves space and eliminates keypresses?
[...]
> I particularly hate it, but Python has lots of good
> things which compesate that (another annoying point
> of Python are slices -- mine are always off by 1).
> I always write explicitly ends as #end, so that I
> can reorganice the code easily if necessary. Maybe
> in the future, when Ruby matures, I could change
> my mind, but currently Python is still my favourite
> scripting language (as formerly was Tcl).
My current impression is that Python is about the best dynamic
language.
It helps that it's one of the most popular such languages.
One of my concerns about it is that it's too big and complex.
I very much favour the smalltalk-inspired idea of keeping
the actual language as small as is reasonably possible.
I wonder if there are any promising new kids on the dynamic
scripting-language block that I haven't heard about yet -
i.e. things not on:
http://dmoz.org/Computers/Programming/Languages/Scripting/Object-Oriented/
http://dmoz.org/Computers/Programming/Languages/Object-Oriented/Prototype-based/
Personally, I'm holding off on any more exploration of dynamic languages
until they all settle on a single VM that they all can run on. The problem
that a new language faces is that it will have a sucky library, and I use
things like Tk or other graphical toolkits for *everything*.
Once you can write a new language and still pull in the entire Python
library (and, ideally, the entire Ruby, Perl, and who knows what else
library), then I think it will be more interesting for me to search out
other languages.
My next language to learn will probably be C#. (On Mono, though.)
>On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
>> As far as grouping by indentation goes, it's why I fell in love with
>> Python in the first place. Â Braces and so on are just extraneous cruft
>> as far as I'm concerned. Â It's the difference between Vietnamese verbs
>> and Latin verbs;-)
>
>Say I buy into the indentation ideology. Python then has this inconsistency: :
>
>Why do we need : at the end of our if and for loops? I spend approximately 6
>minutes/100 lines of code going back and finding all of the times I missed :.
>Is it for cheating?
>
>if False: print ":"
>
>Now, what happened to the whitespace idea here? This code seems very
>unpythonic. I think : is great for slices and lamda where things go on one
>line, but to require it to specify the start of a block of code seems a
>little perlish.
You really don't need a period at the end of a sentences A double
space and a capital is enough to tell you where one sentence ends and
the next one starts Yet, I find the presence of the period makes
written language easier to read in the same way the colon in python
makes code easer to read
;)
Ron
> >> Or, paraphrasing Mark Twain, "Python is the worst possible
> >> programming language, except for all the others."
> Google thinks it's Winston Churchill as well. I did come across a quote
> wiki:
>
> http://www.wikiquote.org/
>
> None of the quotes attributes to Mark Twain looked like the democracy
> quote, though he had a few other good ones related to goverment and
> politics that might be worth a passing glance:
>
> http://en.wikiquote.org/wiki/Mark_Twain
Thanks Kent, thanks Skip.
Wikiquote is nice. I missed it because I googled for Mark Twain and parts of
the Churchill quote -- for that I'm now convinced it is as wikiquote gives
a slightly longer excerpt and the date and location of the speech (November
11, 1947, in the House of Commons).
The closest Mark Twain quote I found is
"We are stopping at Shepherd's Hotel, which is the worst on earth except the
one I stopped at once in a small town in the United States."
http://www.mtwain.com/Innocents_Abroad/58.html
Not very close, though, and the ones on wikiquote are better, too.
Peter
> On Friday 25 March 2005 08:39 am, Ivan Van Laningham wrote:
> Why do we need : at the end of our if and for loops? I spend approximately 6
> minutes/100 lines of code going back and finding all of the times I missed :.
> Is it for cheating?
Because newlines are optional statement terminators. Without the ':',
the end of the statement would depend on the state of the lexer, which
isn't something you want to impose on people.
<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Yes; I have accidentally found that ; can be used also as an optional
statement terminator--when rewriting some perl code.
James
> Wikiquote is nice. I missed it because I googled for Mark Twain and parts of
> the Churchill quote -- for that I'm now convinced it is as wikiquote gives
> a slightly longer excerpt and the date and location of the speech (November
> 11, 1947, in the House of Commons).
Interesting that in the quote on wikiquote, Churchill indicates that the sentiment is not original
with him:
"Indeed, it has been said that democracy is the worst form of government except all those other
forms that have been tried from time to time."
Note the "it has been said"...
Kent
> Interesting that in the quote on wikiquote, Churchill indicates that the
> sentiment is not original with him:
> "Indeed, it has been said that democracy is the worst form of government
> except all those other forms that have been tried from time to time."
>
> Note the "it has been said"...
Back to square one then. When will I ever learn to read...
Peter
>
> "Tim Tyler" <tim@.org> escribió en el mensaje
> news:IDwEr...@bath.ac.uk...
>> What do you guys think about Python's grouping of code via indentation?
>>
>> Is it good - perhaps because it saves space and eliminates keypresses?
>>
>> Or is it bad - perhaps because it makes program flow dependent on
>> invisible, and unpronouncable characters - and results in more
>> manual alignment issues by preventing code formatters from managing
>> indentation?
>
> I particularly hate it, but Python has lots of good
> things which compesate that (another annoying point
> of Python are slices -- mine are always off by 1).
> I always write explicitly ends as #end, so that I
> can reorganice the code easily if necessary. Maybe
> in the future, when Ruby matures, I could change
> my mind, but currently Python is still my favourite
> scripting language (as formerly was Tcl).
>
About slices:
I agree that Python's slice boundaries (some_list[a:b] being all elements
with a <= index < b) are counterintuitive at first. But this method does
satisfy some handy properties, the first of which being:
l[:n] + l[n:] = l
Secondly, the range() function behaves identically to slices, meaning that
for i in range(10):
will iterate 10 times, and
for i in range(len(l)):
will iterate over the indices of the sequence l.
If you had l[a:b] be inclusive on both a and b (instead of inclusive on a
and exclusive on b), you would have to be adding and subtracting one in
all of these examples, leading that much more easily to off-by-one errors.
A digression: my data structures teacher (in c++) has a vector class that
allows you to set upper and lower bounds, and he combines this with for
loops that usually start at one but don't always. I doubt he was trying to
get this point across, but the lesson I've learned is to always start at
zero and count to less than the length of the list (in c, the idiom is
for (i = 0; i < length; i++)). Believe me that any other way will only
lead to trouble! :-)
--
Jacob Lee
jel...@uiuc.edu | www.nearestneighbor.net
>> 3) Sometimes the structure of the algorithm is not the structure
>> of the code as written, people who prefer that the indentation
>> reflects the structure of the algorithm instead of the structure
>> of the code, are forced to indent wrongly.
>
> Do you have any simple examples in mind?
Yes. When I use PyQt (or similar toolkit), I would like to indent my widget
creation code so that one indentiation level means one level down into the
widget tree hierarchy:
v = VBox(self)
# sons of v indented here
w = HBox(self)
# sons of w here
QLabel("hello", w)
QLabel("world", w)
QButton("ok", v)
In fact, I am used to do this very thing in C++, and it helps readability a
lot.
I know I can add "if 1:" to do such a thing, but that's beyond the point. I'm
just showing that there are simple and reasonable examples of cases where you
would like to indent your code in different ways and you can't.
--
Giovanni Bajo
>> things which compesate that (another annoying point
>> of Python are slices -- mine are always off by 1).
>About slices:
Thank you, but I knew the motivations for this
odd behaviour, which can be found as well in, for
example, MetaFont. However, I disagree.
> satisfy some handy properties, the first of which being:
> l[:n] + l[n:] = l
I don't think l[:5] + l[5:] = l is a handy property
and to me is clearly counterintuitive. Further,
I don't understand why l[a:b] has a behaviour which
does't depend on its own logic but on that of certain
constructs containing slices but which aren't the
slices themselves. If you have to add or substract
1 in an expression containing slices (or contained
in a slice), this belongs to the logic of the
expression, not to the slices syntax.
MetaFont explains this by saying that the index
doesn't refer to a character but to a position
between characters, which when traslated to Python
would mean:
s t r i n g
^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6
so that [1:2] is "t".
>> Wikiquote is nice. I missed it because I googled for Mark Twain and parts of
>> the Churchill quote -- for that I'm now convinced it is as wikiquote gives
>> a slightly longer excerpt and the date and location of the speech (November
>> 11, 1947, in the House of Commons).
>
> Interesting that in the quote on wikiquote, Churchill indicates that the sentiment is not original
> with him:
> "Indeed, it has been said that democracy is the worst form of government except all those other
> forms that have been tried from time to time."
>
> Note the "it has been said"...
Though this may be a tricky style issue. I don't know whether some parts
of the country would have cited only the first part, discrediting Mr
Churchill.
In Germany, a sentence like this would be readily welcomed by the "BILD"
newspaper...
Reinhold
> About slices:
>
> I agree that Python's slice boundaries (some_list[a:b] being all elements
> with a <= index < b) are counterintuitive at first. But this method does
> satisfy some handy properties, the first of which being:
> l[:n] + l[n:] = l
And best of all, this is true for _every_ n, at least for the standard
slice implementations...
> Secondly, the range() function behaves identically to slices, meaning that
> for i in range(10):
> will iterate 10 times, and
> for i in range(len(l)):
> will iterate over the indices of the sequence l.
>
> If you had l[a:b] be inclusive on both a and b (instead of inclusive on a
> and exclusive on b), you would have to be adding and subtracting one in
> all of these examples, leading that much more easily to off-by-one errors.
It would be not so much adding/subtracting if list indices started at 1,
but who on earth would want that? ;)
Reinhold
> MetaFont explains this by saying that the index
> doesn't refer to a character but to a position
> between characters, which when traslated to Python
> would mean:
>
> s t r i n g
> ^ ^ ^ ^ ^ ^ ^
> 0 1 2 3 4 5 6
>
> so that [1:2] is "t".
Incidentally, the Python Tutorial tells us exactly the same...
Reinhold
I would call the above an indication of the structure of the output rather
than of the algorithm, which is quite linear. Nonetheless, I can see it as
a reasonable alternate reason for wanting to indent. Thanks for the
response.
Terry J. Reedy
>> s t r i n g
>> ^ ^ ^ ^ ^ ^ ^
>> 0 1 2 3 4 5 6
>>
>> so that [1:2] is "t".
>
> Incidentally, the Python Tutorial tells us exactly the same...
Ah! I've just forgotten that...
Javier
_______________________________________________________________
Javier Bezos | Mem. A multilingual system for LaTeX
jbezos at wanadoo dot es | http://mem-latex.sourceforge.net
.........................|....................................:
>>>3) Sometimes the structure of the algorithm is not the structure
>>> of the code as written, people who prefer that the indentation
>>> reflects the structure of the algorithm instead of the structure
>>> of the code, are forced to indent wrongly.
>>
>>Do you have any simple examples in mind?
>
> Yes. When I use PyQt (or similar toolkit), I would like to indent my widget
> creation code so that one indentiation level means one level down into the
> widget tree hierarchy:
>
> v = VBox(self)
> # sons of v indented here
> w = HBox(self)
> # sons of w here
> QLabel("hello", w)
> QLabel("world", w)
> QButton("ok", v)
>
> In fact, I am used to do this very thing in C++, and it helps readability a
> lot.
But in Python it's really easy to use a declarative construct instead,
maybe something as simple as a nested list of classes and constructor
arguments, and use some simple machinery to build the object graph. This
way you avoid having the code and indentation saying different things,
like in your example above, where it seems that w is not in fact a child
of v. I don't know anything about PyQt though, so if I'm wrong about
that I apologise - but the point still stands, since it's confusing to
read it.
/patrik
--Scott David Daniels
Scott....@Acm.Org
> > I don't think l[:5] + l[5:] = l is a handy property
> > and to me is clearly counterintuitive. Further,
[snipped in the reply]
Please, don't remove parts of my post which are
relevant to the discussion. I said:
>Further,
>I don't understand why l[a:b] has a behaviour which
>does't depend on its own logic but on that of certain
>constructs containing slices but which aren't the
>slices themselves.
You give a counterexample:
> st = "This i a string with typo, for example"
> pos = st.find("i ") + 1 # "+ 1" to get the space after "i"
> new_st = st[:pos] + "s" + st[pos:]
but that shows clearly what I was saying --
this tricky syntax means that you have not
to write st[:pos-1] in this particular code
(but you still have to "write" it in your
mind since it forms part of the logic of the
problem). These kind of hacks look perlish
to me.
Of course, the danger of being off-by-one would
be still present, but I would like to note that
if you change the syntax to avoid it in some
expressions you will find problems in another
expressions where otherwise it wouldn't be
present (counting from the end with negatives
values is particularly funny). The same applies
if the first element is 1 instead of 0, for
example.
Then, why not to leave that to the logic of
the problem and not to tricky syntaxes? A pity,
given that Python has a quite straighforward
syntax.
Javier
What I or you prefer carries very little weight. I know layout-things
stir up a lot of bad feeling, but I honostly think those people should
grow up. When I cooperate in a project, I adapt my style to the one
used in the project. I may use a tool to change between styles for
things I work on an back when I register my piece or I may just write
in the project style, depending on what goes easiest.
> And as not all code I read is code I'm supposed to write (might it be OSS
> that I dig into for debugging, or other 3rd party sources I can't control,
> e.g. different departments with different project leaders) I found that
> python's way of imposing a rather strict layout on _all_ coders out there
> means I've less trouble digging into other peoples code. Which is useful -
> and it seems that I'm not the only one with this feeling.
Well you can't control the languages used either. Personnaly I find
difference in style a very minor issue compared to difference of
language or difference of development environment. If you so
much need the strict layout python imposes, I start to question
whether you are flexible enough for programming.
--
Antoon Pardon
This advise doesn't help.
1) The stuff doesn't has to be spread over multiple pages. One
can have 2 functions, each about three quarter of a page.
The second function will then cross a page boundary.
2) How long is a page? I have worked in differend kind of
environments where the number of lines per page could
differ from 35 to 70.
>> 3) Sometimes the structure of the algorithm is not the structure
>> of the code as written, people who prefer that the indentation
>> reflects the structure of the algorithm instead of the structure
>> of the code, are forced to indent wrongly.
>
> Do you have an example?
About any time I have need of a break.
--
Antoon Pardon
But then we are back at the problem of different styles.
People argue they like the python rule, because they have
difficulties with the different styles that are allowed
by the free form that is allowed in othe languages.
>> 2) It makes it hard to introduce some kind of new syntax constructs.
>
> I consider this as much a plus as a minus ;-)
I can see your point. We don't want an avalance of new constructs
and some restraint is needed but I feel python is too restraint
here.
>> 3) Sometimes the structure of the algorithm is not the structure
>> of the code as written, people who prefer that the indentation
>> reflects the structure of the algorithm instead of the structure
>> of the code, are forced to indent wrongly.
>
> Do you have any simple examples in mind?
Essentially each time I need to use:
if condition break.
IMO this part of the code is usualy a control for a loop and thus
of the same level as
while condition:
--
Antoon Pardon
The advice "don't write a function longer than a page" is as good advice
today as it was 30 years ago, but the definition of "a page" has changed.
In the old days, "a page" pretty much meant 66 lines, because that's what
fit on a standard sheet of line printer paper (minus a few lines for
headers and footers).
These days, "a page" pretty much means "a window", which are scrollable so
your function always starts at the top of one. Of course, there is no
standard for how long a window is, but...
> 2) How long is a page? I have worked in differend kind of
> environments where the number of lines per page could
> differ from 35 to 70.
I would say 35 to 70 lines seems like a reasonable limit for how long a
function should be :-) The system I'm working with now is fill with 500
line functions and 700 line functions. Believe me, 70 lines would be a
blessing compared to that.
The bottom line is not a rigid line count. The goal is to be able to
understand what the function is doing in one gulp.
They maybe should grow up - but that's true about a great deal of things in
life, and still doesn't happen. And the extra effort is there - regardless
of your degree of acceptance of it. I and lots of others prefer not having
that extra effort.
> Well you can't control the languages used either. Personnaly I find
> difference in style a very minor issue compared to difference of
> language or difference of development environment. If you so
> much need the strict layout python imposes, I start to question
> whether you are flexible enough for programming.
I can easily reply on this that if you insist on more freedom in layout, I
start to question if you are flexible enough for programming - if it's so
unimportant, why don't you adapt? You certainly do, but it still bothers
you.
And I don't need it so much - I just take it and like it and don't bother.
Your own statements make it clear that you care about layout as much as I
do, and usually every reasonable programmer does.
So we are back to the question _which_ layout to chose - and I (and lots of
others, that certainly have made a measurable impact on the python language
and stuff build on top of it, thus they can be seen as flexible
programmers....) made the point that _one_ layout saves time and effort.
And if it really is so important for you to have your own layout, create a
prepocessor and do it - I want to do that myself one day I find the time,
not for every-day tasks but for cases like python-embedded-in-html where
the whitespace-dependency collides with the layouting-requirements of html.
--
Regards,
Diez B. Roggisch
Once upon a time, one could put a literal ASCII pagefeed char (^L I
believe) in a comment between the two functions to put each on its own
page. I have not tried this on Windows, though.
Terry J. Reedy
It can be quite useful for inserting something into a list (or string),
after finding the position where you wish to insert it.
improvedList = l[:n] + [new stuff] + l[n:]
I'm very fond of Python's slice indexing - it makes a number of things
fairly easy, for example:
myList[:N] # first N items
myList[-N:] # last N items
myList[start:start+N] # N items, from start position
# chunk a list into smaller lists (or strings into smaller strings)
# (thanks to Thorsten Kampe for the original example)
def chunky(sequence, N):
for i in range(len(sequence)/N + bool(len(sequence) % N)):
print sequence[i*N:(i+1)*N] # no off-by-one errors here :-)
myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
N = 3
chunky(myList, N)
which returns:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
Note you can leave out the bool part if you don't want that partial
chunk at the end.
I vaguely remember hearing at one stage that the
sequence[position:position+length] notation is also potentially useful
for indexing into large strings or buffers.
Alex Martelli stated back in 2001, when this issue was previously
discussed:
> it IS just an extension of what Koenig
> explains in his book "C Traps and Pitfalls", about how
> always using half-open ranges helps avoid off-by-one
> errors that otherwise tend to plague programs.
Regards, Myles.
Oops, I missed Dennis Lee Bieber's working example of exactly that.
My apologies.
Regars, Myles.
In many languages, C and Python included, the formfeed (^L) is just another
piece of whitespace. You don't even need to comment it.
C:\Tmp>type x.py
print "before"
^L
print "after"
C:\Tmp>x.py
before
after
C:\Tmp>
(Pedantic note: I cheated there. My cmd session did not really say "^L".
It gave me the symbol for female, which is code point 12 in the default
character set. I translated it to the VIM equivalent to make the point.)
--
- Tim Roberts, ti...@probo.com
Providenza & Boekelheide, Inc.
As I answered in another post this is not more
useful than writing l[:n-1]. Of course, I'm aware
of the case where n=0, but this would require only
a bit of extra code (and, after all, I'm just saying
that half-open ranges are not a panacea and that I
don't like their side effects).
> I vaguely remember hearing at one stage that the
> sequence[position:position+length] notation is also potentially useful
> for indexing into large strings or buffers.
Right, to some extent it's useful, but at the cost
of introducing tricky syntaxes for very specific
cases, like this one, and unexpected off-by-one
errors in other cases, which is my point. For
example, recently I had to get a value from a
list preceded by the two previous values:
lst[n-2:n+1] and not the more logical (at last
to my eyes) lst[n-2:n].
Instead of giving further examples I would like
to cite three cases:
1) You have a starting point (s) and a
length (t): lst[s:s+t].
2) You have an ending point (e) and a
length: lst[e-t+1:e+1].
3) You have a starting point and an ending
point: lst[s:e+1].
What's odd is that Python applies the syntax of
case 3 to the logic of case 1. While something
like lst[s:s+t-1] for the first case could be
explained in simple mathematical terms (in other
words, it's an integral part of the algorithms),
I cannot find a way to explain the e+1 in cases
2 and 3 (and the inconsistency with e-t+1 in case
2 vs. s+t in case 1) except the Python syntax.
Javier
_______________________________________________________________
Javier Bezos | Mem. A multilingual system for LaTeX
jbezos at wanadoo dot es | http://mem-latex.sourceforge.net
.........................|....................................
If you use the "slice indices represent points between
the elements" mental model, then you don't have an
ending point here, you have one less than the ending
point -- hence it's not surprising that you need to
add 1.
> 3) You have a starting point and an ending
> point: lst[s:e+1].
Again, you don't really have an ending point.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
While this may be an interesting philosophical (or should that be
philological) discussion, since Python has worked this way for donkey's
years, and since a change would break 30% of the existing codebase, you
clearly can't be advocating change.
So, what's the point of this thread now?
regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/