One-line raise if

python support

expression_a if xxx else expression_b

which's equal to :

xxx ? expression_a : expression_b (of C)

But

statement_a if xxx

is not acceptable.


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

Tags:

Python