On 02/09/2021 04:32, Steven D'Aprano wrote:
On Wed, Sep 01, 2021 at 03:40:37PM +0200, Peter Otten wrote:
Instead of removing it you might add a filter to get a similar effect:
[...]
warnings.filterwarnings("always", "woof!")
Unfortunately that's too aggressive. In my use-case, `bark` will be called many, many times in a loop, and so potentially "woof" will be displayed over and over again. That will be annoying.
Once it has been displayed *once* in that loop, it shouldn't be displayed again for the rest of the loop.
Also, `bark` is being called from a comprehension or sort key function, so it is difficult to keep an explicit flag myself:
# My use case is *not* this def process(values): seen = False for item in values: if condition: if seen: bark() seen = True
# More like this: sorted(values, key=func) # func may call bark
Allowing `bark` to *always* display could be annoying. Ideally I want it to be displayed *at most* once per call to sorted(). I can do that by removing the filter after sorting. Or at least I could if it were possible to remove individual filters.
Then use filterwarnings("once", ...):
import warnings def bark(): warnings.warn("woof!")
for i in range(6): print(i) if i == 3: warnings.filterwarnings("once", "woof!") bark()
0
Warning (from warnings module):
File "