-2

How to improve the following if conditional in Python 3.6 to one line.

def run_cmd(beta: bool): {
  cmd = "cloud create {}".format(self.name)
  if beta:
    cmd = "cloud beta create {}".format(self.name)
}
6
  • 7
    Just remove the if statement since you are setting beta to False and there is nothing in your code that will change that. Commented Feb 9, 2019 at 23:27
  • 1
    Something like cmd = "cloud beta create {}".format(self.name) if beta else "cloud create {}".format(self.name)? That's assuming, of course, the value of beta could change. Commented Feb 9, 2019 at 23:30
  • 1
    Well in the same way they could just go for cmd = "cloud create " because beta is false and name is empty :) Bad question Commented Feb 9, 2019 at 23:30
  • 1
    if beta was not staticly fixed: cmd = "cloud {}create {}".format("beta " if beta else "", self.name) Commented Feb 9, 2019 at 23:30
  • 1
    OP, I'm afraid your question is currently somewhat confusing. It would probably be best to reformulate your question and clearly state what you're trying to achieve. Commented Feb 9, 2019 at 23:33

3 Answers 3

1

The following one liner will achieve it:

cmd = "cloud {}create {}".format("beta " if beta else "", name)
Sign up to request clarification or add additional context in comments.

Comments

1

One way to achieve this:

cmd = "cloud{} create {}".format(["", " beta"][beta], self.name)

3 Comments

Is it really better? Much less readable. Not always converting things to one line make things better.
I prefer explicit stuff, so for me I would leave it as is in the original question. I like using the boolean as the index though. Neat.
better = more efficient ? I don't know. better = more readable ? I don't know too :) It depends... You even can write this f"cloud {'beta ' if beta else ''}create {name}" in Python3 (since you prefer the A if cond else B construction).
1

If you want to reduce the if statement:

name = ''
beta = True

cmd = "cloud beta create {}".format(name) if beta else "cloud create {}".format(name)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.