Trailing comma (was: Re: structure in Python)

Alex Martelli aleax at aleax.it
Tue Oct 21 09:37:51 EDT 2003


Timo Virkkala wrote:

> Ben Caradoc-Davies wrote:
>>     d = {
>>         "A": [1, 5],
>>         "B": [6, 7],  # last trailing comma is optional but good style
>>     }
> 
> Why is it considered good style? I mean, I understand that it's easier
> to later add a new line, but... 

Exactly.  You'll save a lot of trouble.

> Most places (SQL comes first to mind,
> since I've just done a lot of work with Python and databases) don't
> accept a trailing comma in a similar situation, so if I get into the
> habit of including the trailing comma, I'll just end up tripping myself
> up a lot.

C, C++, and, I believe, Java all allow such trailing commas too.  It's
basically a consensus among modern programming languages (SQL isn't).

Learning to use different style in SQL is not going to be difficult,
because it's such a hugely different language from all of these
anyway.  Are you afraid to use a * for multiplication because it may
confuse you to write 'select * from ...'?-)

Plus, there are errors which are either diagnosed by the computer
or innocuous (extra commas are typically that way), and others which
are NOT diagnosed and can be terribly dangerous (missing commas may be).
E.g., consider:

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

print "we have", len(x), "thingies"

This prints "we have 3 thingies" -- as a comma is missing after
"fie", it's automatically JOINED with the following "foo", and
x is actually ['fee', 'fiefoo', 'fum'].  VERY insidious indeed
unelss you have very good unit tests (C &c all have just the same
trap waiting for you).

Do yourself a favour: ALWAYS add trailing commas in such cases
in Python, C, C++, etc.  The occasional times where you'll do
so in SQL and get your knuckles rapped by the SQL engine, until
you finally do learn to do things differently in the two "sides"
of things (SQL on one side, Python, C or whatever on the other),
will be a minor annoyance; a missing comma might take you a LONG
time to diagnose through its subtly wrong effects - there's just
no comparison.


Alex





More information about the Python-list mailing list