簡體   English   中英

條件表達式上的 raise 語句

[英]raise statement on a conditional expression

遵循“武士原則”,我試圖在我的功能上做到這一點,但似乎是錯誤的......

return <value> if <bool> else raise <exception>

有沒有其他“美麗”的方式來做到這一點? 謝謝

內聯/三元if是表達式,而不是語句。 你的嘗試意味着“如果bool,返回值,否則返回raise expression的結果” - 這當然是無稽之談,因為raise exception本身就是一個語句而不是表達式。

內聯無法做到這一點,你不應該這樣做。 明確地做:

if not bool:
    raise MyException
return value

如果你絕對要raise在表達式中,你可以做

def raiser(ex): raise ex

return <value> if <bool> else raiser(<exception>)

如果函數中沒有無條件raise ,則“嘗試”返回raiser()的返回值,該值將為None

我喜歡用斷言來做,所以你要強調那個成員必須像合同一樣。

>>> def foo(self):
...     assert self.value, "Not Found"
...     return self.value

好吧,你可以分別測試bool:

if expr: raise exception('foo')
return val

這樣,您可以在之前測試expr

有一種方法可以在三元內部提高,訣竅是使用exec

def raising_ternary(x):
    return x if x else exec("raise Exception('its just not true')")

正如你所看到的,用True調用它會做三元的第一部分,用False調用它會引發異常:

>>> def raising_ternary(x):
...     return x if x else exec("raise Exception('its just not true')")
... 
>>> raising_ternary(True)
True
>>> raising_ternary(False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in raising_ternary
  File "<string>", line 1, in <module>
Exception: its just not true
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM