[英]python type hints for none or something
考慮以下代碼段
uri_match: Optional[Match[str]] = re.match(r"https//(.+?)/(.+)", "bla bla")
re.match
的類型為Match
或 None。
res = uri_match.group(1)
此行表示None
沒有成員group
。 這意味着類型檢查器看到返回可能是None
並因此引發錯誤。 我們如何處理這些?
static 類型檢查器告訴您,如果您的re.match
調用未能找到模式(因此uri_match
為None
),第二次調用也將失敗,但缺少方法除外。
你如何解決這個問題取決於你的程序的正確行為是什么。 也許您有一些可以分配給uri_match
(或res
)的后備值,或者您可以獲得不同的"bla blah"
字符串並在其上再次嘗試匹配。
或者,一個失敗的匹配可能會使代碼的 rest 毫無意義,並且任何回退都需要在程序邏輯的某個更高級別發生。 在這種情況下,引發異常可能是正確的做法(盡管返回像None
這樣的特殊值可能是一種可能的選擇)。
以下是一些示例代碼,它們在放棄之前經歷了一些不同的突發事件:
uri_match: Optional[Match[str]] = re.match(r"https//(.+?)/(.+)", "bla bla")
if uri_match is None:
uri_match = re.match(r"https//(.+?)/(.+)", "foo bar") # try another input
if uri_match is not None:
res = uri_match.group(1) # condition this line, so it only runs when we have a match
elif default is not None:
res = default # maybe there's some default result we can use?
else:
raise ValueError("Invalid input") # if not, raise an exception
... # use res below
您的代碼可能不會做所有這些事情,但一兩個可能對您的程序有意義。
您可以通過if
或try-except
來處理它。如果您害怕在代碼庫周圍使用太多if
或try-except
,您可以使用 function 來獲得結果。 所有重復的if
或try-except
都將被 function 覆蓋,因此無需擔心。
通過if
代碼處理:
import re
def handle_by_if(s):
uri_match = re.match(r"https://(.+?)/(.+)", s)
if uri_match:
return uri_match.group(1)
print(f"handle_by_if: {s} not match anything")
return ""
print(handle_by_if("https://stackoverflow.com/questions"))
print("-"*20)
print(handle_by_if("bla bla"))
結果:
stackoverflow.com
--------------------
handle_by_if: bla bla not match anything
通過try-except
代碼處理:
def handle_by_try_except(s):
uri_match = re.match(r"https://(.+?)/(.+)", s)
try:
return uri_match.group(1)
except AttributeError:
print(f"handle_by_if: {s} not match anything")
return ""
print(handle_by_try_except("https://stackoverflow.com/questions"))
print("-"*20)
print(handle_by_try_except("bla bla"))
結果:
stackoverflow.com
--------------------
handle_by_if: bla bla not match anything
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.