Skip to content

Instantly share code, notes, and snippets.

@arnavm
Last active July 31, 2019 05:10
Show Gist options
  • Save arnavm/c8ae8c8f4b27b27da2b7eb17e5c32734 to your computer and use it in GitHub Desktop.
Save arnavm/c8ae8c8f4b27b27da2b7eb17e5c32734 to your computer and use it in GitHub Desktop.
Debug warnings in Python
# Example of catching warnings to set debugging breakpoints; based on
# https://docs.python.org/3/library/warnings.html#testing-warnings
import warnings
# Toy function to throw a warning
def fxn():
warnings.warn("deprecated", DeprecationWarning)
# Context manager to catch warning
with warnings.catch_warnings(record=True) as w:
# In this case, debug a DeprecationWarning;
# more warnings here: https://docs.python.org/3/library/warnings.html#warning-categories
warnings.simplefilter("always", category=DeprecationWarning)
# Insert code here that triggers a warning
fxn()
# If warning was thrown...
if len(w) > 0:
# Set breakpoint here for debugging
print("You were warned!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment