Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python warning showing always instead of once

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?

like image 716
postelrich Avatar asked Oct 31 '22 09:10

postelrich


1 Answers

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()
like image 104
Noctis Skytower Avatar answered Nov 15 '22 04:11

Noctis Skytower