Skip to content

Python: debug

최적화 관련

인터프리터에서 __debug__ 변수가 구현되는 방식은 최적화되어 있어서 추가적인 if문의 제어흐름 로직은 코드에 실제로 포함되지 않는다. dis 패키지를 사용해 확인해 볼 수 있다.

from dis import dis


def main():
    print("run test.py", __debug__)

    if __debug__:
        print("debug run")
    else:
        print("release run")


main()

dis(main)

그래서 다음과 같이 사용해 -O 옵션에 따른 해당 main 함수의 중간 언어를 살펴보면,

c:\temp> python test.py
run test.py True
debug run
  6           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('run test.py')
              4 LOAD_CONST               2 (True)
              6 CALL_FUNCTION            2
              8 POP_TOP

  9          10 LOAD_GLOBAL              0 (print)
             12 LOAD_CONST               3 ('debug run')
             14 CALL_FUNCTION            1
             16 POP_TOP
             18 LOAD_CONST               0 (None)
             20 RETURN_VALUE
c:\temp> python -O test.py
run test.py False
release run
  6           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('run test.py')
              4 LOAD_CONST               2 (False)
              6 CALL_FUNCTION            2
              8 POP_TOP

 11          10 LOAD_GLOBAL              0 (print)
             12 LOAD_CONST               3 ('release run')
             14 CALL_FUNCTION            1
             16 POP_TOP
             18 LOAD_CONST               0 (None)
             20 RETURN_VALUE

보는 바와 같이 if 문으로 인한 COMPARE_OP 자체가 없습니다.

See also

Favorite site