cool-RR / PySnooper

Never use print for debugging again
MIT License
16.31k stars 954 forks source link

Add Callback #245

Closed CypressVillage closed 1 year ago

CypressVillage commented 1 year ago

Thank you for bringing us such a powerful and convenient program. šŸ˜ƒ

I want users to be able to customize the behavior when pysnooper catches the right frame. This allows pysnooper to do more than output information in the console. To achieve it we just need to leave a simple interface for the user, like this:


### Writing elapsed time: #############################################
#                                                                     #
_FOREGROUND_YELLOW = self._FOREGROUND_YELLOW
_STYLE_DIM = self._STYLE_DIM
_STYLE_NORMAL = self._STYLE_NORMAL
_STYLE_RESET_ALL = self._STYLE_RESET_ALL

start_time = self.start_times.pop(calling_frame)
duration = datetime_module.datetime.now() - start_time
elapsed_time_string = pycompat.timedelta_format(duration)
indent = ' ' * 4 * (thread_global.depth + 1)
self.write(
    '{indent}{_FOREGROUND_YELLOW}{_STYLE_DIM}'
    'Elapsed time: {_STYLE_NORMAL}{elapsed_time_string}'
    '{_STYLE_RESET_ALL}'.format(**locals())
)

self.on_elapsed_time(indent, elapsed_time_string)  # We can add an interface here

#                                                                     #
### Finished writing elapsed time. ####################################

Then we can add the corresponding empty function, so that programmers who need it can implement it:

class Tracer:
    def __init__()
        ...
        self.on_elapsed_time = lambda indent, elapsed_time_string:None  # we just need an empty function
        ...

The same is true elsewhere

I'm probably new to the programming world, so I don't really understand the potential harm that such a modification can do to the project (at least not in my opinion). I sincerely hope you will consider my suggestion. If you allow it, I'll submit pull requests after I've made the changes.

cool-RR commented 1 year ago

The harm is in the maintenance burden. Giving people lots of freedom results in more people submitting bugs when they do bad things with this freedom. Also, there are already too many features in PySnooper, and as we add more features, the possibility for features to clash with each other grows exponentially. PySnooper is intentionally designed to be a small, simple tool.

If you want to do this, you should probably edit your local copy of PySnooper, or monkeypatch it.