gruns / icecream

🍦 Never use print() to debug again.
MIT License
9.07k stars 184 forks source link

[Enhancement] Add enable/disable as contextmanager #125

Open jfthuong opened 2 years ago

jfthuong commented 2 years ago

It could be nice to temporarily enable/disable icecream with something like:

with ic.disable():
    call_my_super_function_without_icecream()

To disable the icecream printing temporarily.

gruns commented 2 years ago

neat idea!

how often do you find yourself doing this?

alexmojaki commented 2 years ago

I think it would be straightforward to make the existing enable() and disable() return context managers, so they could be used like this, without affecting existing usage. So ic.enable() would immediately set enabled = True while returning an object whose __exit__ sets enabled = False.

Marrin commented 2 years ago

Sounds a little bit to simple because then you can't nest this, i.e. if any code call_my_super_function_without_icecream() uses, does the same to disable debugging output for some chunk of code the __exit__ there would enable too early. Maybe a counter that keeps track of how many nested disabled blocks are currently active would solve that.

alexmojaki commented 2 years ago

Good point. The implementation would need to be slightly more complicated than what I described. Still seems doable without changing the existing API or creating new functions or arguments.

jfthuong commented 2 years ago

neat idea!

how often do you find yourself doing this?

Actually, I just discovered 🍦 few days ago so ... not that often! :) But I believed it would be interesting.

gruns commented 2 years ago

@jfthuong this is an interesting idea and would be great to support!

do you have the time and/or inclination to build this with tests? if so, that'd be awesome 🙌

Sounds a little bit to simple because then you can't nest this, i.e. if any code call_my_super_function_without_icecream() uses, does the same to disable debugging output for some chunk of code the exit there would enable too early.

if this feature would be used heavily -- which im still not sure if would be -- then nesting support would be nice

but as i dont think it will be used heavily, i'm ok to ship ic.enable() and ic.disable() as context managers without nesting support. and we would then note:

  1. the lack of nesting support in the docs, and
  2. ask for contributions to add nesting support

shipped and useful but imperfect is better than perfect but not shipped. and i think most people would use it without nesting

cristobal-sifon commented 2 years ago

This can also be achieved by creating different instances for different purposes:

from icecream import IceCreamDebugger
ic1 = IceCreamDebugger()
ic2 = IceCreamDebugger()
ic1.disable()
x = 3
y = 4
ic1(x)
ic2(y)

will only produce ic| y: 4