How to disable assert statements inside a module?

Bengt Richter bokr at oz.net
Sun Mar 10 19:41:56 EST 2002


On Sun, 10 Mar 2002 16:17:01 -0500, Tim Peters <tim.one at comcast.net> wrote:

>[Pearu Peterson]
>> Is there a way to disable all assert statements inside a module,
>> and without calling python with -O switch?
>
>[Martin v. Loewis]
>> You can set __debug__ to 0 on the module level; this will disable
>> assert statements inside this module.
>
>Note that assignment to __debug__ was deprecated in 2.1:
>
>    SyntaxWarning: can not assign to __debug__
>
>and removed in 2.2:
>
>    SyntaxError: can not assign to __debug__
>
>-O is the only way left.  Guido often writes code under the control of an
>explicit "debug" vrbl instead.  A more flexible way to control asserts would
>be (IMO) prime PEP material (as a heavy assert user myself, I sympathize
>with Pearu's dilemma -- "all or nothing everywhere" is too crude for large
>projects with many subsystems).
>
Controlling logging would also be handy. I.e., not just controlling its execution,
but including/excluding it from compiled code.

Play with the idea of a built-in compiler line filter based on name token matching:

E.g., the compiler could include or exclude lines with the name token 'assert'
by default, depending on allow/deny config data set up or overridden in site.py,
and possibly overridable within a module scope.

This could be controlled globally also by command line option.

You could exclude whole imports by filtering on the module name, and thus exclude
the import effects. By suitable naming (even just using modulename.xxx for
all uses, and isolating them on single lines), you could leave a lot of
cruft in the source and not suffer performance hits in execution of .pyc's.

Conventions for default exclusions of enableable standard modules (and calls using
them) like the proposed logging module could be established.

Regards,
Bengt Richter




More information about the Python-list mailing list