ANNOUNCE: A Python 2.1 release candidate!

Andrew Dalke dalke at acm.org
Sat Apr 14 03:44:17 EDT 2001


Don O'Donnell wrote:
>    if __debug__: print "function bleep entered with arg: %s" % arg
>thus all debugging is under control of a single variable.

That's an expected use of the __debug__ variable.  Indeed,
the docs say that code will be ignored when generating bytecode
under the -O option.

>I find it very useful to be able to assign to __debug__.  There are at
>least two situations where I use it regularly:
>
>1.  As a run-time debugging switch.  By providing an interactive user
>option switch which sets __debug__ to 0 or 1 dynamically at run time
>through user input (menu or command prompt).  This allows me to easily
>turn off debugging when it's not needed and turn it back on when it is.
>This can save me a lot of time in not having to watch thousands of lines
>of unneeded debugging information scroll up my screen.  Especially true
>in early stages of testing, where I just want the compiler diagnostics
>and run-time exception handler to do my first level checking.

As compared to using some other variable, like "DEBUG = 1" ?
It you are concerned about performance and want the -O
to not compile the debug code, and allow toggling of debug status
information when not using -O, then this works fine.

  if __debug__:
    if DEBUG:
      print "Here I am!"

(I believe you have to nest the statements like this since the
compiler isn't clever enough to check for "__debug__ and DEBUG".
No constant subexpression analysis in the compiler.)

This is at the cost of 1 more line.  If that's too much, you
can write things like:

def debug(*args):
  print string.join(map(str, args)) + "\n"

if __debug__:
  debug("I am here with val=", val)


>2.  To selectively turn off debugging for sections of code or functions
>which have been tested, and turn it on for code sections under test.

What's wrong with a DEBUG variable in the module?  Otherwise you are
overriding a builtin variable with a module variable.

Also, many people use debug levels, which you can't get out
of the __debug__ variable.  Or do you start wanting to assign
numbers to it besides 0 and 1?

>Can anyone explain to me why this change, to make __debug__ read only,
>is necessary or beneficial in some way?  Or am I misinterpreting GvR's
>statement that "assignment to __debug__ ... will become illegal in 2.2."

It is not a misinterpretation if my reading of python-dev is
correct.  The thing is that __debug__ changes the compile-time
semantics so that a run-time change in its value, like

 ======
import os
if os.environ.get("DEBUG") == "1":
  __debug__ = 1
else:
  __debug__ = 0

if __debug__:
  print "Importing this module"
 ===

will not work as expected if run under -O.  If it is a read-only
value then there can be no confusion.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list