Even with the parens, a comma is needed:
>>> ("Godot")
'Godot'
>>> ("Godot",)
('Godot',)
Without a comma, it’s not a tuple literal with one item, but instead is an expression enclosed in parens.
Even with the parens, a comma is needed:
>>> ("Godot")
'Godot'
>>> ("Godot",)
('Godot',)
Without a comma, it’s not a tuple literal with one item, but instead is an expression enclosed in parens.
Lest I mislead, it needs to be mentioned that optional enclosure within parentheses is not a special case for tuples. Like a number or a string literal, a tuple literal is an expression, and an expression enclosed within parentheses evaluates to the value of the expression:
>>> ('To parenthesize or not to parenthesize, that is the question')
'To parenthesize or not to parenthesize, that is the question'
>>> ('To parenthesize or not to parenthesize, that is the question',)
('To parenthesize or not to parenthesize, that is the question',)
The comma there is what makes the second one a tuple literal.
Because it’s so easy to miss a lone trailing comma.
I would also favor using parentheses. It does make it clearer that it is a tuple. Since sometimes it is necessary to have them, using parentheses may as well be considered the:
... one --obvious way to do it.
No, the comma defines a tuple, whether you write x = "Godot",
or x = ("Godot",)
. The only thing parentheses do is prevent the comma from being parsed as part of the syntax of some other construct, such as in a function call. f(x, y)
calls f
with two arguments; f((x,y))
calls f
with a single argument. Or perhaps more relevant to the singleton-tuple case, f(x,)
calls f
with x
as its argument, while f((x,))
calls f
with a tuple containing x
. (Function calls allow trailing commas in their argument lists.)
So, with tuples, the parentheses are harmless, and in many cases do serve a purpose. Other types of objects such as dictionaries, strings, and lists are easily distinguished visually via their delimiters, while tuples can lie bare, and thereby require more visual effort to discern. With that noted, it seems beneficial to surround them with parentheses, even when they are superfluous, for the sake of ease of reading. Is there any disadvantage to supplying them that anyone here would like to note?
Only that in some cases they are so routine that parentheses are a distraction and typically not recommended by style guidelines, such as return x, y
or for i, e in enumerate...
.
That’s plausible. If it is anticipated that the returned tuple value will likely be utilized directly for a tuple assignment when the function is called, the styles of the code in both locations would be in synchrony with each other.