0

I am using a function from an imported module within an optimization loop. As a consequence the function gets called 10s or 100s of times. Since this is an optimization, sometimes the test parameters will cause a warning to be raised in the function being called (for example, because they are below a threshold value). I'm ok with these warnings, but I don't need them to appear 100s of times in my terminal. I am fine with manually checking the resulting parameters after the optimization has completed.

Is there some kind context manager that can be used to suppress any calls to logger.warning just for this function call?

An extra wrinkle is that the imported module is using loguru for logging. I'm not sure if that necessitates a different solution or not.

Drphoton
  • 164
  • 9
  • Have you looked into `contextlib.suppress`? What have you tried already? – JRiggles Aug 25 '23 at 15:58
  • Hey JRiggles, thanks for asking. I tried 2 things yesterday but I forgot to write down what they were. From memory... One was to disable logging before and re-enable it afterwards. It was something like: logging.disable(logging.WARNING) function_call() logging.disable(logging.NOTSET) The second method was a context manager, I think it was catchwarnings() or something like that. Sorry I'm trying to format my code but it isn't working in comments :) – Drphoton Aug 25 '23 at 16:03
  • [this](https://docs.python.org/3/library/contextlib.html#contextlib.suppress) might be worth checking out! – JRiggles Aug 25 '23 at 16:04
  • I don't have an Exception to suppress, though, it's a call to logger.warning(), which just prints text to terminal – Drphoton Aug 25 '23 at 16:08
  • Hmm...damn, that is trickier. Maybe `filterwarnings` can help? [see here](https://stackoverflow.com/a/30368735/8512262) - as a bonus, you should be able to use that in conjunction w/ `suppress` if you're so inclined – JRiggles Aug 25 '23 at 16:09
  • I've just tried the following, and it's not working: with warnings.catch_warnings(): warnings.simplefilter("ignore") function_call() I think the issue is this is a call to logger.warning(), not warning.warn() – Drphoton Aug 25 '23 at 16:24

0 Answers0