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.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.
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).
You can use a simple helper function:
>>> def my_raise(ex): raise ex
>>> x = 1 if False else my_raise(ValueError('...'))
ValueError: ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With