On Thu, Sep 2, 2021 at 7:36 PM Peter Otten <__pete...@web.de> wrote: > > 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 "<pyshell#145>", line 2 > UserWarning: woof! > 1 > 2 > 3 > > Warning (from warnings module): > File "<pyshell#145>", line 2 > UserWarning: woof! > 4 > 5 > > For good performance you'd ideally provide the lineno, but I don't see a > clean way to get that. >
That has the side effect that all OTHER warnings get their onceness reset too though. >>> warnings.warn("hello") <stdin>:1: UserWarning: hello >>> warnings.warn("world") <stdin>:1: UserWarning: world >>> warnings.warn("hello") >>> warnings.warn("world") >>> warnings.filterwarnings("once", "hello") >>> warnings.warn("hello") <stdin>:1: UserWarning: hello >>> warnings.warn("world") <stdin>:1: UserWarning: world (It's actually the same as resetfilters, and for the same reason - whenever the filters change, all oncenesses get forgotten.) ChrisA _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/7INM4BE2SFPG3ABLNIKOUNOHWDKA7TL2/ Code of Conduct: http://python.org/psf/codeofconduct/