私はいくつかの特殊なワークフローを監視するために書いたPythonモジュールの潜在的な競合状態を解消しようと、Pythonの「許可よりも許しやすい」(EAFP)コーディングスタイルについて学びました。 try/except if/thensを使用していたブロックを除きます。Pythonでどのくらいの頻度でカスタム例外を定義する必要がありますか?
私はPythonの初心者です。このEAFPスタイルは論理的に意味があり、コードはより堅牢に見えますが、これについては何かが船外に感じられます。メソッドごとに1つ以上の例外を定義するのは悪い習慣ですか?
これらのカスタム例外は、1つのメソッドに対してのみ有用である傾向があり、機能的に正しい解決策のように感じますが、維持するコードが多いようです。ここで
例のサンプル方法:
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