How to throw exceptions using ternary operator in Python

2

I want to throw an exception on a single line to a method that a boolean has to receive if he does not receive it, by using a ternary operator. How can I do it? I tried to put a else pass but it does not validate the syntax

def metodo(self,boleano):
        try:
            raise ValueError('Se esperaba un boleano') if not isinstance(boleano, bool) else pass
            #Implementar el resto del metodo

        except ValueError as errorPropio:
            print(errorPropio) 

Note: I know how to implement it in more lines and it works. I want the raise to work in one, thanks

    
asked by Cesar Augusto 11.08.2018 в 18:03
source

2 answers

2

Be careful, the expression you are looking for does not really do what you expect.

The "ternary"% syntax a if b else c requires that both a as b , as c are expressions, that is, have a value (the b will be interpreted by the context as a boolean). It is intended to be used on the right side of an assignment, as in:

r = a if b else c

Neither a , nor b , nor c can be commands, but expressions (a call to a function counts as an expression, since it returns a value and then the returned value would be used).

raise is not an expression. It is a command. That's why this does not work:

r = raise Exception() if b else c

Not this:

r = a if b else raise Exception()

Not this:

a if b else raise Exception()

So how does this work?

raise Exception() if b else c

Well, because Python is seeing it like this:

raise (Exception() if b else c)

That is, the ternary operator is being applied to decide which exception is raised, and not to decide whether or not an exception is raised. If b is evaluated as true, the exception Exception() will be raised and if not, the exception result of evaluating c .

If you try:

raise ValueError('Se esperaba un boleano') if not isinstance(boleano, bool) else None

then if you do not have the boolano, ValueError() will be raised, but if you have the boolean it will try to raise None , which is not a valid exception and will cause another exception TypeError ( exceptions must derive from BaseException )

The recommended form would therefore be:

if not isinstance(boleano, bool): raise ValueError('Se esperaba un boleano')

that is also a single line and more readable.

    
answered by 11.08.2018 / 19:07
source
2
def error():raise ValueError('Se esperaba un boleano')

def metodo(booleano):
    try:
        isinstance(booleano, bool) or error()
    except ValueError as err:
        print(err)

We define a function that throws an error def error(): and in metodo we verify that the argument booleano is an instance of bool with the method isinstance(booleano, bool) said method returns a True in case if it is an instance and False otherwise. And with the Operator or we verify, in case that isinstance(booleano, bool) is False the function error()

is executed     
answered by 11.08.2018 в 18:27