簡體   English   中英

什么是一個接一個地執行多個條件的pythonic方法,同時向用戶顯示哪個是第一個失敗的

[英]What is the pythonic way to execute multiple conditions, one after the other, while showing to the user which is the first to fail

假設我有這個有效的代碼:

def check_some_conds(args):
    assert (condA(args) or
            condB(args))

    assert condC(args)
    assert condD(args)

    return True

(是的,我知道assert很糟糕,但請耐心等一下)

現在,當我調用這個函數時,我可以(或多或少)通過使用except AssertionError:來回溯第一個失敗的斷言,並使用traceback模塊做一些魔術。

但是,這並不理想,因為:

  • assert在python中進行了優化
  • 我無法真正指定錯誤消息
  • 使用追溯模塊充其量只會讓人感到煩惱
  • 我仍然需要獲得一個布爾返回值,所以捕獲它然后更改返回值是樣板代碼。

我正在尋找一種方法:

  • 運行多個條件,大多數是獨立的條件
    • 知道某些功能可能很長並且必須最后嘗試(這里, condD可能需要幾秒鍾
    • 其中一些可能是異步函數或只是內聯評估( a == b
  • 返回一個布爾值(可選)
  • 記錄一條消息,說condD failednor condA or condB succeded

如果這不可能,請隨時建議我的問題的部分答案

循環你的條件並在最后提出錯誤:

fail = False
for condition in [cond1, cond2, cond3 ...]:

    if not condition(args):
        print(condition.__name__, "failed")
        fail = True
    else:
        print(condition.__name__, "succeeded")
if fail: raise ...

暫無
暫無

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

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