[New-bugs-announce] [issue2420] Faq 4.28 -- Trailing comas

Leszek Dubiel report at bugs.python.org
Wed Mar 19 09:50:47 CET 2008


New submission from Leszek Dubiel <leszek at dubiel.pl>:

This is after discussion on python-ideas: 

http://mail.python.org/pipermail/python-ideas/2008-March/001488.html



I would suggest to add question 4.28 to faq. Everybody who learns Python
reads that and will not ask questions about "one-element tuples". I have
compiled answer from responses to my last question about one-element tuple.



Question: Why python allows to put comma at the end of list? This looks
ugly and seems to break common rules...

Answer: There are may reasons that follow.

1. If you defined multiline dictionary

       d = {                  
           "A": [1, 5],
           "B": [6, 7],  # last trailing comma is optional but good style
       }

it would be easier to add more elements, because you don't have to care
about colons -- you always put colon at the end of line and don't have
to reedit other lines. It eases sorting of such lines too -- just cut
line and paste above.

2. Missing comma can lead to errors that are hard to diagnose. For example:

       x = [
         "fee",
         "fie"
         "foo",
         "fum"
       ]

contains tree elements "fee", "fiefoo" and "fum". So if programmer puts
comma always at the end of line he saves lots of trouble in a future.


2. Nearly all reasonable programming languages (C, C++, Java) allow for an
extra trailing comma in a comma-delimited list, for consistency and to
make programmatic code generation easier. So for example [1,2,3,] is
intentionally correct.


3. Creating one-element tuples using tuple(['hello']) syntax is much much
slower (a factor of 20x here) then writing just ('hello', ).  Trailing
commas
when you only have one item are how python tuple syntax is defined
allowing them to use commas instead of needing other tokens. If python
didn't allow comma at the end of tuple, you will have to use such slow
syntax.


4. The same rule applies to other type of lists, where delimiter can occur
at the end. For example both strings "alfa\nbeta\n" and "alfa\nbeta" contain
two lines.



Sources:

-- http://mail.python.org/pipermail/python-list/2003-October/231419.html
-- http://mail.python.org/pipermail/python-ideas/2008-March/001478.html
-- http://mail.python.org/pipermail/python-ideas/2008-March/001475.html

----------
assignee: georg.brandl
components: Documentation
messages: 64050
nosy: dubiel, georg.brandl
severity: normal
status: open
title: Faq 4.28 -- Trailing comas

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue2420>
__________________________________


More information about the New-bugs-announce mailing list