Recipe 8.1. Disabling Execution of Some Conditionals and LoopsCredit: Chris McDonough, Srinivas B, Dinu Gherman ProblemWhile developing or debugging, you want certain conditional or looping sections of code to be temporarily omitted from execution. SolutionThe simplest approach is to edit your code, inserting 0: # right after the if or while keyword. Since 0 evaluates as false, that section of code will not execute. For example: if i < 1: doSomething( ) while j < k: j = fleep(j, k) into: if 0: # i < 1: doSomething( ) while 0: # j < k: j = fleep(j, k) If you have many such sections that must simultaneously switch on and off during your development and debug sessions, an alternative is to define a boolean variable (commonly known as a flag), say doit = False, and code: if doit and i < 1: doSomething( ) while doit and j < k: j = fleep(j, k) This way, you can temporarily switch the various sections on again by just changing the flag setting to doit = True, and easily flip back and forth. You can even have multiple such flags. Do remember to remove the doit and parts once you're done developing and debugging, since at that point all they would do is slow things down. DiscussionOf course, you have other alternatives, too. Most good editors have commands to insert or remove comment markers from the start of each line in a marked section, like Alt-3 and Alt-4 in the editor of the IDLE IDE (Integrated Development Environment) that comes with Python; a common convention in such editors is to start such temporarily commented-out lines with two comment markers, ##, to distinguish them from "normal" comments. One Python-specific technique you can use is the _ _debug_ _ read-only global boolean variable. _ _debug_ _ is true when Python is running without the -O (optimize) command-line option, False when Python is running with that option. Moreover, the Python compiler knows about _ _debug_ _ and can completely remove any block guarded by if _ _debug_ _ when Python is running with the command-line optimization option, thus saving memory as well as execution time. See AlsoThe section on the _ _debug_ _ flag and the assert statement in the Language Reference and Python in a Nutshell. |