1

Can this be simplified to a single one-liner, without the one liner being more difficult to read?

if self.is_running:
    return

self.is_running = True

Something like:

return if self.is_running else self.is_running = True

(Obviously the above won't work, just an example of what i'm looking to achieve)

TRG
  • 663
  • 1
  • 7
  • 17
  • 1
    I don't think so. – Guybrush Apr 12 '19 at 09:00
  • 1
    I think you cant return and not return in the same line, thats point of return – amonowy Apr 12 '19 at 09:05
  • 1
    You could put the `return` on the same line as the `if` statement: `if self.is_running: return`. But that's as far as you can reduce the LOC here I think. – glhr Apr 12 '19 at 09:08
  • Was just a thought really, but your explanation makes sense. Should I delete the question or wait for someone to answer so no one else asks such a stupid question in future? :P – TRG Apr 12 '19 at 09:08
  • 1
    @Plopp that's simply incorrect. You can't use assignments in a conditional expression. See https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator – glhr Apr 12 '19 at 09:11
  • Oo true, my bad, I overlooked that part – Plopp Apr 12 '19 at 09:12

1 Answers1

1

What you're trying to achieve with return if self.is_running else self.is_running = True is called a conditional expression. However, you cannot use any kind of statement (eg. self.is_running = True) in a conditional expression. A conditional expression should take the form:

a if condition else b

where b is a value not a statement.

In your case, the shortest code you can achieve is something like:

if self.is_running: return
self.is_running = True
glhr
  • 3,982
  • 1
  • 13
  • 24