[Tutor] __debug__ and PYTHONOPTIMIZE

Peter Otten __peter__ at web.de
Tue Jul 5 04:07:16 EDT 2022


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


More information about the Tutor mailing list