Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
JE_Muc Avatar asked Feb 22 '19 10:02

JE_Muc


People also ask

How do you raise errors in Python?

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.

Can we use if without else in Python?

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.

What is ?: In Python?

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.

How can the ternary operator be used in Python?

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.


2 Answers

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).

like image 185
bruno desthuilliers Avatar answered Oct 14 '22 02:10

bruno desthuilliers


You can use a simple helper function:

>>> def my_raise(ex): raise ex

>>> x = 1 if False else my_raise(ValueError('...'))
ValueError: ...
like image 34
user200783 Avatar answered Oct 14 '22 02:10

user200783