[英]Python check all values below are not None
檢查以下所有值的最佳方法是不是None。 這是我嘗試過的:
user = url_string.get('user', None)
subject = url_string.get('subject', None)
email = url_string.get('email', None)
from_address = url_string.get('from_address', None)
if not any(user, subject, email,from_address):
raise Exception('missing data')
由於您希望定義所有這些代碼,因此以下代碼將非常pythonic。 以來
比許可更容易請求寬恕。 這種常見的Python編碼風格假設存在有效的鍵或屬性,並且如果假設被證明是錯誤則捕獲異常。 這種干凈和快速的風格的特點是存在許多try和except語句。 該技術與許多其他語言(如C)共有的LBYL風格形成對比。
https://docs.python.org/2/glossary.html
try:
user = url_string['user']
subject = url_string['subject']
email = url_string.get['email']
from_address = url_string['from_address']
except KeyError:
raise Exception('missing data')
正如評論中所提到的,這確實留下了字典中的一個值為None並且可以通過測試的可能性。 但是,我假設您使用get('...',None)
假設字典不包含空值。 如果確實包含空值,請考慮Moses Koledoye的解決方案。
您可以在變量的可迭代中檢查None
的包含:
if None in (user, subject, email, from_address):
raise Exception('missing data')
或者更好的是仍然將您的代碼置於try /除了KeyError
之外,並在處理異常時引發自定義異常。
嘗試這個:
if None in [user, subject, email,from_address]:
raise Exception('missing data')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.