I'm trying to use warnings.simplefilter
to display my warning once. I've created a subclass to DeprecationWarning
. I tried putting the simplefilter
in the same module as my warning, and in the package level init as far to the top I could but it will always display the warning on every call. Tested in python 3.4.
my warning:
class MyDeprecationWarning(DeprecationWarning):
pass
how I'm calling simplefilter:
warnings.simplefilter('once', MyDeprecationWarning)
how I'm calling warn:
warnings.warn("Warning!", MyDeprecationWarning)
What's the issue?
If your program is running multiple times or some code in running in a separate process, you may have not issued your commands in the right order. The following program works as expected.
import warnings
class MyDeprecationWarning(DeprecationWarning):
pass
def main():
print('Program Starting')
warnings.simplefilter('once', MyDeprecationWarning)
for _ in range(100):
warnings.warn('Warning!', MyDeprecationWarning)
print('Program Finished')
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With