postelrich
postelrich

Reputation: 3496

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?

Upvotes: 6

Views: 2277

Answers (1)

Noctis Skytower
Noctis Skytower

Reputation: 22001

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()

Upvotes: 3

Related Questions