我正试图把raise if压缩成一行。我有:
def hey(self, message):
if not message:
raise ValueError("message must be a string")它可以工作,但这段代码不起作用:
def hey(self, message):
raise ValueError("message must be a string") if not message我得到了SyntaxError: invalid syntax。我做什么好?
发布于 2013-11-07 07:17:41
.... if predicate在Python中是无效的。(你是从Ruby来的吗?)
使用如下:
if not message: raise ValueError("message must be a string")更新
若要检查给定消息是否为字符串类型,请使用isinstance
>>> isinstance('aa', str) # OR isinstance(.., basestring) in Python 2.x
True
>>> isinstance(11, str)
False
>>> isinstance('', str)
Truenot message不做你想做的事。
>>> not 'a string'
False
>>> not ''
True
>>> not [1]
False
>>> not []
Trueif not message and message != '':
raise ValueError("message is invalid: {!r}".format(message))发布于 2013-11-07 07:32:11
python支持
expression_a if xxx else expression_b相当于:
xxx ? expression_a : expression_b (of C)但
statement_a if xxx是不可接受的。
发布于 2020-03-23 01:02:22
这是一个老问题,但这里还有另一个选项,它可以给出相当简洁的语法,而不存在assert的一些缺点(例如当使用优化标志时它就消失了):
def raiseif(cond, msg="", exc=AssertionError):
if cond:
raise exc(msg)适用于这一具体问题:
def hey(self, message):
raiseif(
not isinstance(message, str),
msg="message must be a string",
exc=ValueError
)https://stackoverflow.com/questions/19830040
复制相似问题