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?

  • 2
    condition expressions require an else clause too, hence the syntax error. – Ashwini Chaudhary Nov 7 '13 at 7:19
  • @hcwhsa thats the point I missed. Thanks! – leemour Nov 7 '13 at 8:25
  • 1
    "Condensing" this to a one-liner is not pythonic, just keep it as it is. As a side note, an empty string evaluates to False, so either your test is broken or your message error is wrong. – bruno desthuilliers Nov 7 '13 at 8:27
  • @brunodesthuilliers didn't know this type conversion, it makes a difference. – leemour Nov 7 '13 at 8:51
  • 1
    @leemour : if message is a string, then not message and message != '' is redundant since the empty string has a false value. FWIW all python objects have a truth value, which defaults to True unless the class says otherwise, cf docs.python.org/2/reference/datamodel.html#object.__nonzero__ – bruno desthuilliers Nov 7 '13 at 11:03

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

Use following:

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


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

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

not message does not do what you want.

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

if not message and message != '':
    raise ValueError("message is invalid: {!r}".format(message))
  • another option is he is influenced by list comprehensions – alko Nov 7 '13 at 7:35
  • I don't want to explicitly validate if it's a string as it's against duck typing. Probably, the error message isn't correct but I couldn't come up with a better one. – leemour Nov 7 '13 at 8:14
  • 1
    @leemour, How about "message is empty." ? – falsetru Nov 7 '13 at 8:17
  • @falsetru this validation checks against False as well, but I think your message is better:) – leemour Nov 7 '13 at 8:23
  • @leemour, If True is passed, what should happen? – falsetru Nov 7 '13 at 8:52

python support

expression_a if xxx else expression_b

which's equal to :

xxx ? expression_a : expression_b (of C)


statement_a if xxx

is not acceptable.

  • statement_* should be expression_*. – falsetru Nov 7 '13 at 7:33
  • 3
    x ? y : z is not a valid syntax for python – alko Nov 7 '13 at 7:34
  • @alko please pay attention to the "Of C " inside bracket. – oyjh Sep 20 '18 at 6:24

From your code, it seems you are asking how to check if the input is a string type. Based on the updated answer from @falsetru, I would suggest the following. Note that I have changed the error to TypeError as it is more appropriate for this case

def hey(msg):
    if not isinstance(msg, str): raise TypeError

PS! I know this is an old post. I am just posting in case others find it useful ;)


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):
        not isinstance(message, str),
        msg="message must be a string",
  • This is longer than the code the OP wanted to condense, and adds the additional cost of calling an additional function. – chepner Mar 23 '20 at 2:00
  • Fair point on the additional cost of the function call. Regarding the code length, it's actually the same length if you remove the keyword arg names and incorporate the isinstance logic as suggested in the top answer. It's if not isinstance(message, str): raise ValueError("message must be a string") vs raiseif(not isinstance(message, str), "message must be a string", ValueError). Generalizing, the raiseif function will be more compact than the standard if/raise approach if you are looking for something similar to assert that doesn't get removed with -O. That's how I got here. – totalhack Mar 23 '20 at 2:39

Your Answer

