Reputation: 36715
I have a function with some user warning:
warnings.warn(message)
I want to make it display the message only at the first time it is encountered, and then become silent.
The closest thing I found in the docs was to issue, at the program start:
warnings.simplefilter('once', UserWarning)
But it does not seem to work - I get the same warning many times in the same program.
How can I do this?
Upvotes: 2
Views: 549
Reputation: 51643
You could construct a class that does and memoizes given warnings for you:
class WarnOnlyOnce:
warnings = set()
@classmethod
def warn(cls,message):
# storing int == less memory then storing raw message
h = hash(message)
if h not in cls.warnings:
# do your warning
print(f"Warning: {message}")
cls.warnings.add(h)
WarnOnlyOnce.warn("First warning")
WarnOnlyOnce.warn("First warning") # skipped - identical spelling
WarnOnlyOnce.warn("Second warning")
WarnOnlyOnce.warn("First warning") # skipped - identical spelling
WarnOnlyOnce.warn("First warning") # skipped - identical spelling
WarnOnlyOnce.warn("Last warning")
WarnOnlyOnce.warn("LAst warning") # different spelling
WarnOnlyOnce.warn("LASt warning") # different spelling
WarnOnlyOnce.warn("LAST warning") # different spelling
Output:
Warning: First warning
Warning: Second warning
Warning: Last warning
Warning: LAst warning
Warning: LASt warning
Warning: LAST warning
Upvotes: 1