Python claims to work with -O

I am trying to make sure python is not running when using -O. However, my test program indicates that it always runs. I specifically use -O on the command line, and I used -O when I ran setup.py using build and installation. Before I submit a bug report, I wanted to make sure that I did not make mistakes rookie ...

So do I need to do something else or another so that assert does not execute?

My simple script:

print __debug__

if __debug__:
    print "True branch"
else:
    print "False branch"

assert(False)

works when run offline. Print:

False
False branch

When I copy this snippet in the main program (which I cannot include here ...), I get:

False
True branch
AssertionError

I am completely confused how this can happen. This is Python 2.7.6 on Mac. (Sorry for the Mac, I have to use it to work.)

+4
1

, .pyc -O. , . :

  • .py -O ( )
  • .pyc -O
  • .pyo -O.

.pyc -O .pyo , , .

, if __debug__, .pyc .pyo . , -O, __debug__, , .

, Tracker Python , : - .pyo -O.

: , , "debug_example.py", :

noether:Desktop mdickinson$ cat debug_example.py
def main():
    print "__debug__ is {}".format(__debug__)
    if __debug__:
        print "__debug__ is True"
    else:
        print "__debug__ is False"

if __name__ == '__main__':
    main()

, -O , :

noether:Desktop mdickinson$ python2 debug_example.py
__debug__ is True
__debug__ is True
noether:Desktop mdickinson$ python2 -O debug_example.py
__debug__ is False
__debug__ is False

"debug_example.pyc", py_compile . ( , , setup.py.):

noether:Desktop mdickinson$ python2 -m py_compile debug_example.py
noether:Desktop mdickinson$ ls -l debug_example.pyc
-rw-r--r--  1 mdickinson  staff  350 24 Mar 21:41 debug_example.pyc

debug_example.pyc, (), -O, Python :

noether:Desktop mdickinson$ python2 -O debug_example.pyc
__debug__ is False
__debug__ is True

Python dis module, - :

Python 2.7.6 (default, Nov 18 2013, 15:12:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import debug_example
>>> import dis
>>> dis.dis(debug_example)
Disassembly of main:
  2           0 LOAD_CONST               1 ('__debug__ is {}')
              3 LOAD_ATTR                0 (format)
              6 LOAD_GLOBAL              1 (__debug__)
              9 CALL_FUNCTION            1
             12 PRINT_ITEM          
             13 PRINT_NEWLINE       

  4          14 LOAD_CONST               2 ('__debug__ is True')
             17 PRINT_ITEM          
             18 PRINT_NEWLINE       
             19 LOAD_CONST               0 (None)
             22 RETURN_VALUE        

, -, if: '__debug__ is True'.

: .pyc .pyo: .py Python , .pyc .pyo.

+3

Source: https://habr.com/ru/post/1533223/


All Articles