첫째, 필자의 접근 방식이 적절한 지 잘 모르겠다. 그래서 나는 다양한 제안을한다.자주 반복되는 try/except in Python
try/except 문이 코드에서 자주 반복되는 경우이를 단축하거나 완전히 쓰지 않는 것이 좋습니다.
try:
# Do similar thing
os.remove('/my/file')
except OSError, e:
# Same exception handing
pass
try:
# Do similar thing
os.chmod('/other/file', 0700)
except OSError, e:
#Same exception handling
pass
예를 들어, 하나의 선 행동에 대한 당신은 예외 처리 래퍼를 정의한 다음 람다 함수 전달할 수 :
def may_exist(func):
"Work with file which you are not sure if exists."""
try:
func()
except OSError, e:
# Same exception handling
pass
may_exist(lambda: os.remove('/my/file'))
may_exist(lambda: os.chmod('/other/file', 0700))
이 '솔루션은 그냥 일이 덜 명확하게 하는가를? 방금 try/except 문을 모두 써야하나요?
[파이썬? : 예외 처리 표현으로]의 중복 가능성 (http://stackoverflow.com/questions/7088009/python-try-except-as -an-expression) – agf
Me와 @kindall은 어제이 질문에 매우 답했습니다. – agf
@agf :이 질문은 부분적으로 관련이있는 것 같습니다. 링크 해 주셔서 감사합니다. 그러나 Ned Batchelder의 대답은 예외를 잡을 필요가있는 코드 블록에서 기능을 만들 필요가 없다는 장점이있는 것으로 보입니다. – sutre