Add `raise ... if ...` syntax to `raise` statement without `else`

There was a discussion about this on StackOverflow, where the user asked how to implement the Samurai principle (Return victorious, or not at all.)
It will be great if the such syntax was added for the raise statement (without needing the preceding else)

Example:

raise if not something

raise X(*args, **kwargs) if error

The such syntax can also be added for the return statement

AFAIK this can be implemented even without changing the current grammar, but only adding the fallback route in AST or something.

Dimitriy.

Why not if error: raise ... ?

4 Likes

Because there will be no need to create a new block, and also the example above is more readable and cleaner

Another example and comparison:

if not x:
    raise
raise X(A, B, C)

vs

raise if not x
raise X(A, B, C)

Also as I said, this is easier to implement comparing to other feature requests, and at least adds new syntax (which is a bit rare in python)

The proposed syntax is harder to read for me (understood, this is a personal preference), and even ignoring that, adds almost nothing in terms of brevity or clarity over the currently valid syntax. If you don’t like the extra indented line, you can even use

if not x: raise
raise X(A, B, C)
6 Likes

[quote]

raise if not x
raise X(A, B, C)

I understand the last line. It’s just current Python syntax.

But I don’t understand the first line. What is being raised? ValueError? NameError? SyntaxError?

Blocks are cool. Blocks are good. But if you don’t want a block, you can write the current test+raise as a one-liner:

if not success: raise SomeException(arg)

No new syntax required.

What preceding else? The raise statement doesn’t need a preceding else, and testing for some condition doesn’t require an else either.

No, this change would in fact require a change to the grammar, because your proposal isn’t currently valid syntax. It might even be a fairly difficult change, because raise Exception if x else BaseException is already valid syntax, and it may be complicated to distinguish the two. Implementing this change in a toy project could be a good exercise for learning more about how the Python parser works.

Regardless, even if a proposed syntax change is very easy to implement, that’s not a great argument for including it. The bar for new syntax is very high, and as the other posters in this thread have said, there’s a lot of arguments against this particular proposal.

4 Likes