IT 지식 창고

(Python) try vs if 써야 하는 상황

casim 2020. 8. 11. 22:45

원문 : https://stackoverflow.com/questions/1835756/using-try-vs-if-in-python

 

Using try vs if in python

Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a va...

stackoverflow.com

 

문득, try와 if를 쓰는 상황은 어떨 때이며 코딩하는 사람의 스타일에 따라 다르게 사용되는 것인가를 근본적으로 알아보고 싶어졌습니다.

 

Python에서는 LBYL style (Look Before You Leap)보다 EAFP style(Easier to Ask for Forgiveness than Permission)을 사용하도록 권장합니다. 

즉, EAFP는 어떤 것을 검사하기전에 일단 실행하여 예외처리를 하는 try except문에 가깝고,

LBYL은 어떤 것을 실행하기전에 에러가 날만한 요소를 조건절로 검사하는 if문에 가깝습니다.

 

그렇다면, python에서는 try문을 활용하는 것을 권장할 것이며, 아래의 내용은 try와 if문의 효율성에 관한 내용입니다.

 

stackoverflow에서 글쓴이는 try는 99%로 에러가 발생하지 않을 경우 try를 사용하고, 50%의 확률로 에러가 발생하지 않을 경우 if문을 사용한다고 합니다.

import timeit
timeit.timeit(setup="a=1;b=1", stmt="a/b") # no error checking
0.06379691968322732

timeit.timeit(setup="a=1;b=1", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.0829463709378615

timeit.timeit(setup="a=1;b=0", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.5070195056614466

timeit.timeit(setup="a=1;b=1", stmt="if b!=0:\n a/b")
0.11940114974277094

timeit.timeit(setup="a=1;b=0", stmt="if b!=0:\n a/b")
0.051202772912802175

효율성을 볼 때, try문에서 except 처리를 할 때, if문보다 5배 ~ 10배 느린 것을 볼 수 있습니다.

하지만, if문은 에러가 나지 않는 경우보다 더 빠르게 처리할 수도 있어서 효율성을 비교하기에는 무리가 있어보입니다.

 

python document에서는 왜 EAFP의 스타일을 권장하는지는 정확히 모릅니다. 혹여나 궁금하시다면 아래 사이트를 참고하세요..

https://docs.python.org/3.8/glossary.html#term-eafp

 

Glossary — Python 3.8.5 documentation

The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example, int(3.15) converts the floating point number to the integer 3, but in 3+4.5, each argument is of a different type

docs.python.org

저는 try는 99%로 에러가 발생하지 않을 경우 try를 사용하고, 50%의 확률로 에러가 발생하지 않을 경우 if문을 사용한다라는 말에 더 동의를 하여 이와 같은 스타일로 코딩을 합니다.

 

결국 try문과 if문을 사용하는 것은 본인 스타일인 것 같습니다. ㅎㅎ,,