[Tutor] reason(s) for trailing comma in dict declarations

Peter Otten __peter__ at web.de
Sat Aug 25 18:07:13 CEST 2012


akleider at sonic.net wrote:

> Part of a previous post:
> """
> Here's the style I'd use:
> 
> combos = {
>   0: 'id',
>   2: 'country',
>   3: 'type',
>   5: 'lat',
>   6: 'lon',
>   12: 'name',
> }
> 
> Put each entry on its own line, indented by two spaces, and leave a
> trailing comma on the last entry. The latter is especially important
> in sequences of strings to prevent them from being
> "silently"<=>"concatenated" if you were to add an entry and forget the
> comma.
> """
> 
> When I first saw this I thought it would lead to a syntax error so tried
> it out..
> Then played with it to try to recreate the '"silently"<=>"concatenated"'
> problem but couldn't.  I like this syntax because it avoids the syntax
> error if the comma is omitted when adding an entry but I don't understand
> the (potential) concatenation problem.
> 
> Could you explain please?

Consider the following list:

>>> ["the"
... "quick",
... "brown"
... "fox"]
['thequick', 'brownfox']

"the" and "quick" look like two entries in the list, but as the comma is 
missing they are merged together. Same for "brown" and "fox".
I think you cannot run into this problem with dictionaries as accidentally 
merging a value and a key would result in a syntax error at the second 
colon:

>>> {"the": "quick"
... "brown": "fox"}
  File "<stdin>", line 2
    "brown": "fox"}
           ^
SyntaxError: invalid syntax




More information about the Tutor mailing list