Search code examples
pythontuplesreadability

Inline Tuple Creation - Which is More Readable?


I'm trying to decide how I should handle creating tuples inside method calls from a readability perspective.

The standard way seems to make it easy to overlook the parentheses of the tuple, especially if it's inside several nested calls:

Foo(a, b).bar((c, len(d)))

So far, I've come up with two different ways that I could make it obvious a tuple is being created. I could explicitly call the tuple() function, such as:

Foo(a, b).bar(tuple(c, len(d)))

Or, I could expand the line a bit to make the tuple parentheses more obvious:

Foo(a, b).bar(
    (c, len(d))
)

Which of these should be preferred or considered more "pythonic"? Or is there a better way to approach this?


Solution

  • Instead of this:

    Foo(a, b).bar((c, len(d)))
    

    Just expand it:

    foo = Foo(a, b)
    barparam = (c, len(d))
    foo.bar(barparam)
    

    Easy to read, easy to modify, easy to code review after modification.