0

Quite frequently, I have written lines like

if arg == foo: return bar

It is naturally a one-liner, at the beginning of a function body. Notice there is no else, it just returns on a special value of the parameter, and proceeds with the normal flow of the function otherwise.

Still, it feels like the order is wrong. In perl it is possible to write (modulo some $'s)

return bar if arg == foo

which feels more natural. Matter of taste, I know.

Is there a pythonic way of writing something after a return word that would impose a condition on the return statement?

It is, of course, possible, that there is no way.

  • A condition can be imposed within the return statement, but it *will return* unconditionally; the condition can only affect *what* is returned. See the linked duplicate for details. It's not clear to me why "the order feels wrong" to you; this kind of guard clause is a standard and common idiom in many contemporary programming languages. Intuitively to me, it would be strange if a line started with `return` and then sometimes did not return. – Karl Knechtel Jan 08 '23 at 09:28
  • 1
    Please [edit] the question to clarify what should happen if the condition is not met. – MisterMiyagi Jan 08 '23 at 09:31
  • 2
    @MisterMiyagi: It should do what `if arg == foo: return bar` does: keep going. – user2357112 Jan 08 '23 at 09:36
  • 1
    This is also what the Perl construct mentioned in the question does. – user2357112 Jan 08 '23 at 09:36
  • @KarlKnechtel Perl is structured to mimic English expressions, so such a construct would not be out of place. Think of it as "Buy six eggs if they have any in store." – MisterMiyagi Jan 08 '23 at 09:37
  • 1
    No, there's no equivalent to Ruby's or Perl's "backwards if" in Python. – deceze Jan 08 '23 at 09:39
  • @deceze interesting find; I didn't expect that there would be a more specific duplicate. I corrected it again to use the canonical, though. ;) However: it should be noted that the `and` trick in the accepted answer there **will not work** for `return`, because `return` is a *statement, not an expression*. Some other answers explain this in more detail. – Karl Knechtel Jan 08 '23 at 09:40
  • 1
    @Karl That's not quite equivalent, since that example attempts a conditional *expression*, not a conditional *statement*. — Edit: as you note yourself… – deceze Jan 08 '23 at 09:42
  • 1
    I don’t think the second duplicate is appropriate because `return` is not an expression. That makes practically all workarounds aside from formatting incompatible. – MisterMiyagi Jan 08 '23 at 09:43
  • It does not sit well with me that we are closing something as a duplicate of X rather than Y, given that X is strongly negatively scored and also marked as a duplicate of Y. – Karl Knechtel Jan 08 '23 at 09:48
  • 1
    X should not have been closed as a duplicate of Y either. – user2357112 Jan 09 '23 at 11:09

0 Answers0