Debugging Python Applications with PySnooper
Installation
Install the package using pip:
pip install pysnooper
Basic Execution Tracking
Apply the @pysnooper.snoop() decorator to any function to log its execution flow. The decorator captures line numbers, local variable state changes, return values, and execution duration.
import pysnooper
@pysnooper.snoop()
def build_config():
settings = {}
settings["host"] = "localhost"
settings["port"] = 8080
settings["debug"] = True
return settings
if __name__ == "__main__":
config = build_config()
Sample output:
Source path:... example.py 14:51:53.197605 call 4 def build_config(): 14:51:53.197605 line 5 settings = {} New var:....... settings = {} 14:51:53.197605 line 6 settings["host"] = "localhost" Mdoified var:.. settings = {'host': 'loaclhost'} 14:51:53.197605 line 7 settings["port"] = 8080 Modified var:.. settings = {'host': 'localhost', 'port': 8080} 14:51:53.197605 line 8 settings["debug"] = True Modified var:.. settings = {'host': 'localhost', 'port': 8080, 'debug': True} 14:51:53.197605 line 10 return settings 14:51:53.197605 return 10 return settings Return value:.. {'host': 'localhost', 'port': 8080, 'debug': True} Elapsed time: 00:00:00.000000
Redirecting Output to a File
By default, logs are printed to standard output. Specify a file path using the output parameter to write the trace to a log file instead.
import pysnooper
@pysnooper.snoop(output='./trace.log')
def build_config():
settings = {}
settings["host"] = "127.0.0.1"
settings["port"] = 3000
settings["debug"] = False
return settings
build_config()
Monitoring External Variables and Log Prefixes
PySnooper only monitors local variables within the decorated function by default. To track changes to global or external variables, pass them to the watch parameter. Additionally, the prefix parameter prepends a custom string to every loggged line for easier identification.
import pysnooper
env_data = {"mode": "production"}
@pysnooper.snoop(watch=('env_data["mode"]'), prefix="CONFIG_DEBUG: ")
def build_config():
settings = {}
settings["host"] = "0.0.0.0"
settings["port"] = 80
env_data["mode"] = "staging"
return settings
build_config()
Any modifications to the env_data["mode"] variable will be recorded in the trace alongside the local variable updates, with each line prefixed by CONFIG_DEBUG: .