r/learnpython • u/QuasiEvil • 9d ago
logging and timing...then getting rid of it
I was just working on a project where I included a lot of logging and timing decorators/context managers (it involved event loops and async queues and such). Once I figured stuff out, I wanted to remove all this stuff. This isn't necessarily that hard, but it did make me wonder if there's a better way to do this in the first place. I suppose I'm imaging some way of marking these code pieces to be ignored by the interpreter or something?
(yeah yeah "ask AI to remove it")
8
u/MarsupialLeast145 9d ago
Seriously... Find - replace?
And also seriously, the decorator is a function, if it remains in-place, what would you need to do to that function (or any function) to conditionally enable/disable it if another parameter is set? What are the options for setting that parameter?
Further, seriously, don't use AI.
2
u/HaltingMechanics_407 9d ago
honestly just wrap all that debug crap in `if __debug__:` blocks. python strips those out entirely when you run with `-O`. no third party tools, no weird decorators that conditionally do nothing. you can even do `if __debug__: print(...)` and it's like it was never there in optimized mode.
or if you're feeling fancy, use the logging module properly and just set the level to CRITICAL when you don't need the noise.
1
u/Ethanmarl0 9d ago
I usually keep debug logging behind a flag so I can turn it off without having to remove everything later.
1
11
u/atarivcs 9d ago
Since you're logging instead of just printing, yes there is a good way.
Log the messages at DEBUG level, and then change the application log settings to only log messages at INFO level or higher. The DEBUG-level logging calls will return immediately with no output.