Python: debug
lastmod 2021-10-08created 2021-10-083 edits
Optimization
The interpreter implements the __debug__ variable in an optimized way, so the extra if-statement control flow logic is not actually included in the code. You can check this with the dis package.
from dis import dis
def main():
print("run test.py", __debug__)
if __debug__:
print("debug run")
else:
print("release run")
main()
dis(main)
So if you run it as follows and look at the intermediate language of that main function depending on the -O option,
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
As you can see, there is no COMPARE_OP at all from the if statement.
See also
- Python
- Python:dis - lets you inspect Python ByteCode.