0

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?

Christopher Sheaf
  • 185
  • 1
  • 3
  • 13
  • I don't think it's very common for a function to take a single tuple argument in the first place. (`str.startswith` is the only one I can think of) – chepner Apr 17 '16 at 00:39
  • In C code you see adding a space before and after what's inside parentheses – qwr Apr 17 '16 at 00:42
  • This question is solely opinion based, and as such off-topic for Stack Overflow. That being said, unless you are converting something to a tuple, using the `tuple()` function is *very* uncommon. And it doesn’t seem right to have line breaks for that short chained function call, you would only do that when you get pass some line length limit. An alternative would be to store the tuple in a separate variable first and then just pass the variable, so you don’t have that nested parentheses. And the best option would probably be to change `bar` so it accepts two arguments instead of a tuple. – poke Apr 17 '16 at 00:50
  • 2
    Aside: `tuple(c, len(d))` wouldn't work anyway: it'd need to be `tuple((c,len(d))`. – DSM Apr 17 '16 at 03:27
  • You might as well use a `list` - `[c, len(d)]` there if readability counts. – Antti Haapala -- Слава Україні Apr 17 '16 at 13:13

2 Answers2

1

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

I think I would prefer to rewrite bar as accept two parameters as Foo(a, b).bar(c, len(d)). If you want to use tuple in this case, it can be

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