爲了消除潛在的競爭條件,我編寫了一個python模塊來監控一些專門的工作流程,我學習了python的「比權限更容易請求原諒」(EAFP)編碼風格,現在我提高了大量的自定義異常嘗試/除了我曾經使用如果/ thens的塊。應該在python中定義自定義異常的頻率如何?
我是python的新手,這種EAFP風格在邏輯上有意義,似乎使我的代碼更健壯,但有些事情感覺過度。每種方法定義一個或多個例外是不好的做法?
這些自定義異常往往只對單一方法有用,雖然它感覺像一個功能正確的解決方案,但它似乎有很多代碼需要維護。
這裏有個例子的樣品的方法:
class UploadTimeoutFileMissing(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
class UploadTimeoutTooSlow(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
def check_upload(file, timeout_seconds, max_age_seconds, min_age_seconds):
timeout = time.time() + timeout_seconds
## Check until file found or timeout
while (time.time() < timeout):
time.sleep(5)
try:
filetime = os.path.getmtime(file)
filesize = os.path.getsize(file)
except OSError:
print "File not found %s" % file
continue
fileage = time.time() - filetime
## Make sure file isn't pre-existing
if fileage > max_age_seconds:
print "File too old %s" % file
continue
## Make sure file isn't still uploading
elif fileage <= min_age_seconds:
print "File too new %s" % file
continue
return(filetime, filesize)
## Timeout
try:
filetime
filesize
raise UploadTimeoutTooSlow("File still uploading")
except NameError:
raise UploadTimeoutFileMissing("File not sent")
Python標準庫有大約200k行代碼,並有165個例外 - 確定您需要自己的代碼? (我從一個叫做「[停止寫作課程](http://youtu.be/o9pEzgHorH0)」)的談話中拉出數字 – Glider