0

Is there a better way to do the following:

if condition:
    do_something(argument1, argument2, argument3)
else:
    do_something(argument1, argument2)

I want fewer lines, as it seems too bulky: do_something is a function that takes 2 required arguments and 1 optional argument (uses default value if not passed). I want to pass optional argument (argument3) to this function only if condition == True.

user2864740
  • 60,010
  • 15
  • 145
  • 220
dinenoge
  • 11
  • 1
  • Better how? Faster, more readable, fewer lines, 'sparklier'? I'm not sure there is anything particularly wrong with what you are doing now, any tricks with `*args` calls is only going to be uglier, for little gain. – Martijn Pieters Feb 07 '18 at 15:25
  • 7
    And what is the definition of `do_something()`? Is there a default value for `argument3` if you don't pass one in? – Martijn Pieters Feb 07 '18 at 15:26
  • Your code looks fine as it is--it looks good and its purpose is clear. How does a group of four lines look "bulky"? "Simple is better than complex." – Rory Daulton Feb 07 '18 at 15:45
  • It looks bulky because i have to write `do_something(argument1, argument2` twice – dinenoge Feb 07 '18 at 15:48
  • 1
    `do_something(a, b, *([c] if condition else []))`? – tobias_k Feb 07 '18 at 15:51
  • You can do `args = (argument1, argument2)` \n `if condition: args +=(argument3,)` \n `do_something(*args)`. If you really want to, you can put it all in one line with `do_something(*(argument1,argument2)+condition*(argument3,))`. But, as @MartijnPieters said, it's questionable as to whether this improves the code. – Acccumulation Feb 07 '18 at 15:55
  • If the optional parameter is not used if it is, say, "None" then `do_something(argument1, argument2, argument3 if condition else None)` would be sufficient. See https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator for "inline conditional" expressions (aka. the Python version of the ternary operator). – user2864740 Feb 07 '18 at 20:06
  • If you know what the default value of the third parameter is, you probably can't do better than `do_something(argument1, argument2, default_value if condition else argument3)`. – chepner Feb 07 '18 at 21:41

0 Answers0