What is the syntax rule for having trailing commas in tuple definitions?
Asked Answered
V

10

159

In the case of a single element tuple, the trailing comma is required.

a = ('foo',)

What about a tuple with multiple elements? It seems that whether the trailing comma exists or not, they are both valid. Is this correct? Having a trailing comma is easier for editing in my opinion. Is that a bad coding style?

a = ('foo1', 'foo2')
b = ('foo1', 'foo2',)
Vindicate answered 3/11, 2011 at 9:23 Comment(1)
Here is syntax rule: docs.python.org/reference/expressions.html#expression-listsQuinacrine
U
78

In all cases except the empty tuple the comma is the important thing. Parentheses are only required when required for other syntactic reasons: to distinguish a tuple from a set of function arguments, operator precedence, or to allow line breaks.

The trailing comma for tuples, lists, or function arguments is good style especially when you have a long initialisation that is split over multiple lines. If you always include a trailing comma then you won't add another line to the end expecting to add another element and instead just creating a valid expression:

a = [
   "a",
   "b"
   "c"
]

Assuming that started as a 2 element list that was later extended it has gone wrong in a perhaps not immediately obvious way. Always include the trailing comma and you avoid that trap.

Unapproachable answered 3/11, 2011 at 9:30 Comment(2)
For the reasons stated above, leaving the comma can be advantageous. On the other hand, adopting this habit can lead to headaches if you're also dealing with JavaScript or JSON elsewhere in your application, since some browsers do not like it there.Pluviometer
Yes but, you should never be constructing JSON by hand so that doesn't matter, and for Javascript always use jslint or equivalent to catch that sort of error before it gets near a browser.Unapproachable
F
134

It is only required for single-item tuples to disambiguate defining a tuple or an expression surrounded by parentheses.

(1)  # the number 1 (the parentheses are wrapping the expression `1`)
(1,) # a 1-tuple holding a number 1

For more than one item, it is no longer necessary since it is perfectly clear it is a tuple. However, the trailing comma is allowed to make defining them using multiple lines easier. You could add to the end or rearrange items without breaking the syntax because you left out a comma on accident.

e.g.,

someBigTuple = (
                   0,
                   1,
                   2,
                   3,
                   4,
                   5,
                   6,
                   7,
                   8,
                   9,
                   10,
                   #...
                   10000000000,
               )

Note that this applies to other collections (e.g., lists and dictionaries) too and not just tuples.

Forejudge answered 3/11, 2011 at 9:30 Comment(1)
+1 for pointing out that this is also valid for other stuff than tuples. This is sooo useful for having one key: value, per line, and not take care of comma when adding new stuff.Chroma
U
78

In all cases except the empty tuple the comma is the important thing. Parentheses are only required when required for other syntactic reasons: to distinguish a tuple from a set of function arguments, operator precedence, or to allow line breaks.

The trailing comma for tuples, lists, or function arguments is good style especially when you have a long initialisation that is split over multiple lines. If you always include a trailing comma then you won't add another line to the end expecting to add another element and instead just creating a valid expression:

a = [
   "a",
   "b"
   "c"
]

Assuming that started as a 2 element list that was later extended it has gone wrong in a perhaps not immediately obvious way. Always include the trailing comma and you avoid that trap.

Unapproachable answered 3/11, 2011 at 9:30 Comment(2)
For the reasons stated above, leaving the comma can be advantageous. On the other hand, adopting this habit can lead to headaches if you're also dealing with JavaScript or JSON elsewhere in your application, since some browsers do not like it there.Pluviometer
Yes but, you should never be constructing JSON by hand so that doesn't matter, and for Javascript always use jslint or equivalent to catch that sort of error before it gets near a browser.Unapproachable
F
58

Another advantage of trailing commas is that it makes diffs look nicer. If you started with

a = [
    1,
    2,
    3
]

and changed it to

a = [
    1,
    2,
    3,
    4
]

The diff would look like

 a = [
     1,
     2,
-    3
+    3,
+    4
 ]

Whereas if you had started with a trailing comma, like

a = [
    1,
    2,
    3,
]

Then the diff would just be

 a = [
     1,
     2,
     3,
+    4,
 ]
Falgout answered 8/6, 2013 at 17:42 Comment(1)
This is really more of a comment than an answer to the original question, but I really like the added argument in favor of trailing commas.Venereal
C
16

It's optional: see the Python wiki.

Summary: single-element tuples need a trailing comma, but it's optional for multiple-element tuples.

Carlos answered 3/11, 2011 at 9:31 Comment(0)
B
8

Also, consider the situation where you want:

>>> (('x','y'))*4                         # same as ('x','y')*4
('x', 'y', 'x', 'y', 'x', 'y', 'x', 'y')
#Expected = (('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))

So in this case the outer parentheses are nothing more than grouping parentheses. To make them tuple you need to add a trailing comma. i.e.

>>> (('x','y'),)*4 
(('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))
Bowen answered 28/2, 2018 at 10:28 Comment(1)
Don't think this answer relates the question rather than a misuse of tuple. If we expect the repeated element as a tuple type, we declare the type of this unit as one-element tuple explicitly. Same as with list, try ['x', 'y'] * 4, [ ['x', 'y'] ] * 4, ( ['x', 'y'], ) * 4Urbain
I
7

That's a simple answer.

a = ("s") is a string

and

a = ("s",) is a tuple with one element.

Python needs an additional comma in case of one element tuple to, differentiate between string and tuple.

For example try this on python console:

a = ("s")

a  = a + (1,2,3)

Traceback (most recent call last):

File stdin, line 1, in module

TypeError: cannot concatenate 'str' and 'tuple' objects
Idleman answered 17/7, 2016 at 12:55 Comment(1)
How is this related to the question?! the OP is asking if he needs to put a trailing comma when the tuple has multiple elements: t = (1, 2,) or t = (1, 2)Jenisejenkel
T
6

Trailing comma is required for one-element tuples only. Having a trailing comma for larger tuples is a matter of style and is not required. Its greatest advantage is clean diff on files with multi-line large tuples that are often modified (e.g. configuration tuples).

Theophany answered 3/11, 2011 at 9:29 Comment(0)
F
4

Another reason that this exists is that it makes code generation and __repr__ functions easier to write. For example, if you have some object that is built like obj(arg1, arg2, ..., argn), then you can just write obj.__repr__ as

def __repr__(self):
    l = ['obj(']
    for arg in obj.args: # Suppose obj.args == (arg1, arg2, ..., argn)
        l.append(repr(arg))
        l.append(', ')
    l.append(')')
    return ''.join(l)

If a trailing comma wasn't allowed, you would have to special case the last argument. In fact, you could write the above in one line using a list comprehension (I've written it out longer to make it easier to read). It wouldn't be so easy to do that if you had to special case the last term.

Falgout answered 16/9, 2012 at 1:23 Comment(2)
There would be no need to special-case the last argument, one could just use join in that case: def __repr__(self): 'obj(' + ', '.join([repr(arg) for arg in obj.args]) + ')'.Condiment
It also helps with code generation, even from tools that aren't written in Python and don't have nice functions like join.Falgout
N
4

PEP 8 -- Style Guide for Python Code - When to Use Trailing Commas

Trailing commas are usually optional, except they are mandatory when making a tuple of one element (and in Python 2 they have semantics for the print statement). For clarity, it is recommended to surround the latter in (technically redundant) parentheses.

Yes:

FILES = ('setup.cfg',)

OK, but confusing:

FILES = 'setup.cfg',

When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples).

Yes:

FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )

No:

FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)
Natation answered 17/10, 2018 at 18:29 Comment(0)
V
-7

Coding style is your taste, If you think coding standard matters there is a PEP-8 That can guide you.

What do you think of the result of following expression?

x = (3)
x = (3+2)
x = 2*(3+2)

Yep, x is just an number.

Visor answered 3/11, 2011 at 9:33 Comment(1)
that is a poor way of explaining your line of thought. Explicit is better than implicit.Mckoy

© 2022 - 2024 — McMap. All rights reserved.