파이썬 모듈에서 잠재적 인 경쟁 조건을 제거하기 위해 필자는 일부 특수화 된 워크 플로를 모니터링하기 위해 파이썬의 "EAFP"코딩 스타일보다 "용서를 구하는 것이 더 쉽다"라는 것을 배웠으며 이제는 많은 사용자 지정 예외를 발생시키고 있습니다. try/except if/thens를 사용했다.얼마나 자주 파이썬에서 사용자 정의 예외를 정의해야합니까?
저는 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