JE_Muc
JE_Muc

Reputation: 5774

Raise error in ternary statement in python, without using classic if/else syntax

Is it possible in python to directly raise an error in a ternary statement?

As in:

import numpy as np
y = np.random.rand(200, 5, 5)

y = (y[:, None] if y.ndim == 1 
    else y if y.ndim == 2 
    else raise ValueError('`y` must be given as a 1D or 2D array.'))

Of course it is possible to do this with a simple if/elif/else statement. Thus I'm asking specifically for a solution using a "one-line" ternary statement.

Just for clarification:
I know that ternary statements are not intended to raise errors and that it is not good style according to PEP8 etc.. I am just asking if it is possible at all.

Upvotes: 5

Views: 2117

Answers (3)

Stefan_EOX
Stefan_EOX

Reputation: 1529

You probably shouldn't do it, but you can call an expression that always causes an exception:

y = "foo" if condition else int(None)

This will assign foo to y if condition=True and will raise a TypeError otherwise:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Upvotes: -1

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Plain simple technical answer: NO, it is not possible - as you probably found out by yourself, it yields a SyntaxtError (raise is a statement and the ternary op only supports expressions).

Upvotes: 10

user200783
user200783

Reputation: 14348

You can use a simple helper function:

>>> def my_raise(ex): raise ex

>>> x = 1 if False else my_raise(ValueError('...'))
ValueError: ...

Upvotes: 4

Related Questions