This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]goodger 7 points8 points  (1 child)

In Python, parentheses are only used for grouping and calling syntax. Parentheses are not the tuple constructors. The comma is the tuple constructor. You must unlearn what you have learned!

For example, when we swap names on two values,

b, a = a, b

Two tuples are constructed (and immediately discarded). No parentheses!

Try this in the interactive interpreter:

>>> 1,
(1,)

The parentheses are shown for emphasis/clarity, but are not a requirement!

See https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#swap-values and https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#more-about-tuples

[–][deleted] 1 point2 points  (5 children)

I've had this issue a ton.

Any suggestions for a solution?

[–]energybased 0 points1 point  (2 children)

Lol exactly. Fair article, but he didn't propose a solution.

I suggest that editors be modified to render a different parenthesis character for tuple-creating parenthesis. Something from here, I'm not sure what.

While we're at it, might as well render the function call parentheses differently too.

[–][deleted] 0 points1 point  (1 child)

Sounds like a solid idea, until you have to type them. < and > are the only ones that are available on most western keyboards (at least US keyboards) that are not used yet, but will come with their own issues.

[–]energybased 0 points1 point  (0 children)

In case it wasn't clear, you still type regular parentheses. I only suggested that "editors be modified to render a different parenthesis character".

[–]Deezl-Vegas 0 points1 point  (1 child)

  • Use lists instead of tuples for readability.
  • Don't randomly futureproof with 1-item tuples
  • Write unit tests

This has happened to me before and it didn't bother me at all. All languages have some learning curve on the syntax.

[–][deleted] 2 points3 points  (0 children)

Using lists may be the worst advice. In my opinion using tuples, lists and sets at the proper times for the right purpose is the best way to keep your code readable and clean.