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.

11
  • 1
    Please edit the question to clarify what should happen if the condition is not met. Commented Jan 8, 2023 at 9:31
  • 2
    @MisterMiyagi: It should do what if arg == foo: return bar does: keep going. Commented Jan 8, 2023 at 9:36
  • 1
    This is also what the Perl construct mentioned in the question does. Commented Jan 8, 2023 at 9:36
  • 1
    No, there's no equivalent to Ruby's or Perl's "backwards if" in Python. Commented Jan 8, 2023 at 9:39
  • 1
    @Karl That's not quite equivalent, since that example attempts a conditional expression, not a conditional statement. — Edit: as you note yourself… Commented Jan 8, 2023 at 9:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.