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