Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line raise if

Tags:

python

I'm trying to condense raise if to one line. I had:

def hey(self, message):
    if not message:
        raise ValueError("message must be a string")

It works, but this code doesn't work:

def hey(self, message):
    raise ValueError("message must be a string") if not message

I get SyntaxError: invalid syntax. What do I do?

like image 469
leemour Avatar asked Nov 07 '13 07:11

leemour


People also ask

How do you write an IF condition in a single line Python?

Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.

Can we write if-else in one line?

Other programming languages like C++ and Java have ternary operators, which are useful to make decision making in a single line. Python does not have a ternary operator. But in python, we can use the if-else in a single line, and it will give the same effect as the ternary operator.

How do you write an if-else in one line in R?

Syntax of ifelse() function This returned vector has element from x if the corresponding value of test_expression is TRUE or from y if the corresponding value of test_expression is FALSE . This is to say, the i-th element of result will be x[i] if test_expression[i] is TRUE else it will take the value of y[i] .


2 Answers

.... if predicate is invalid in Python. (Are you coming from Ruby?)

Use following:

if not message: raise ValueError("message must be a string")

UPDATE

To check whether the given message is string type, use isinstance:

>>> isinstance('aa', str) # OR  isinstance(.., basestring) in Python 2.x
True
>>> isinstance(11, str)
False
>>> isinstance('', str)
True

not message does not do what you want.

>>> not 'a string'
False
>>> not ''
True
>>> not [1]
False
>>> not []
True

if not message and message != '':
    raise ValueError("message is invalid: {!r}".format(message))
like image 50
falsetru Avatar answered Oct 14 '22 08:10

falsetru


Old question, but here is another option that can give fairly condensed syntax without some of the drawbacks of assert (such as it disappearing when optimization flags are used):

def raiseif(cond, msg="", exc=AssertionError):
    if cond:
        raise exc(msg)

Applying to this specific question:

def hey(self, message):
    raiseif(
        not isinstance(message, str),
        msg="message must be a string",
        exc=ValueError
    )
like image 27
totalhack Avatar answered Oct 14 '22 08:10

totalhack