vendredi 22 février 2019

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.

Aucun commentaire:

Enregistrer un commentaire