[Tutor] __debug__ and PYTHONOPTIMIZE

Albert-Jan Roskam sjeik_appie at hotmail.com
Tue Jul 5 08:59:18 EDT 2022


   On Jul 5, 2022 10:07, Peter Otten <__peter__ at web.de> wrote:

     On 05/07/2022 00:31, Albert-Jan Roskam wrote:
     >     Hi,
     >     I am using PYTHONOPTIMIZE=1 (equivalent to start-up option "-o").
     As I
     >     understood, assert statements are "compiled away" then. But how
     about
     >     __debug__. Does it merely evaluate to False when using "-o"? Or is
     it also
     >     really gone?

     Why so complicated? Just try and see:

     PS C:\> py -c "print(__debug__)"
     True
     PS C:\> py -Oc "print(__debug__)"
     False

     More generally; how do I decompile a .pyc or .pyo file to
     >     verify this? With the "dis" module? This is a relevant code
     snippet:
     >     for record in billionrecords:
     >         if __debug__:  #evaluating this still takes some time!
     >             logger.debug(record)
     >     Thanks!

     Again: stop worrying and start experimenting ;)

     PS C:\tmp> type tmp.py
     def f():
          if __debug__: print(42)
          assert False
     PS C:\tmp> py -O
     Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:04:37) [MSC v.1929 32
     bit (Intel)] on win32
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import tmp, dis
     >>> dis.dis(tmp.f)
        3           0 LOAD_CONST               0 (None)
                    2 RETURN_VALUE
     >>> ^Z

     PS C:\tmp> py
     Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:04:37) [MSC v.1929 32
     bit (Intel)] on win32
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import tmp, dis
     >>> dis.dis(tmp.f)
        2           0 LOAD_GLOBAL              0 (print)
                    2 LOAD_CONST               1 (42)
                    4 CALL_FUNCTION            1
                    6 POP_TOP

        3           8 LOAD_CONST               2 (False)
                   10 POP_JUMP_IF_TRUE        16
                   12 LOAD_ASSERTION_ERROR
                   14 RAISE_VARARGS            1
              >>   16 LOAD_CONST               0 (None)
                   18 RETURN_VALUE
     _______________________________________________

   ======
   ======
   Thanks Peter, that makes sense. It was half past midnight when I sent that
   mail from my phone. But I agree I should have tried a bit first. 😁
   Best wishes,
   Albert-Jan


More information about the Tutor mailing list