Quickly enable/disable blocks in Python
Sometimes while developing in Python, you need a quick way of enabling or disabling a large block of code for debugging
re = cv2.resize(img[ymin:ymax, xmin:xmax, :], (48, 48))
# Use a multi-line comment
"""
# Enable only if debugging
cv2.imshow("img", re)
cv2.waitKey(5000)
"""
Enabling or disabling this block this way, however, requires quite a bit of scrolling and editing1
Using a slightly different syntax, however, you can quickly flip the block on/off with a single edit:
re = cv2.resize(img[ymin:ymax, xmin:xmax, :], (48, 48))
# To enable, add a # at the start of the line below
#"""
# Enable only if debugging
cv2.imshow("img", re)
cv2.waitKey(5000)
#"""
A block can be enabled by just appending a #
to the comment block starting (#===
), and disabled by removing the #
# Enabled:
#"""
# Enable only if debugging
cv2.imshow("img", re)
cv2.waitKey(5000)
#"""
# Disabled (note the missing #):
"""
# Enable only if debugging
cv2.imshow("img", re)
cv2.waitKey(5000)
#"""
This can be very easily extended to toggling between two code blocks - the blocks can be switched by just appending the #
to the first triple-quote line (or removing it):
# Enable first block
#"""
# Debugging value
PREDICT_THRESHOLD = 1000
"""
# Actual value
# Note that the block comment above does not have a starting #
PREDICT_THRESHOLD = 10
#"""
# Flip to the second block by removing the # from the line below
"""
# Debugging value
PREDICT_THRESHOLD = 1000
"""
# Actual value
# Note that the block comment above does not have a starting #
PREDICT_THRESHOLD = 10
#"""
Footnotes
-
Unless using an IDE - this still requires selecting the code block, though ↩