views:

200

answers:

1

I would like some kind of warning to be raisen as errors, but only the first occurrence. How to do that?

I read http://docs.python.org/library/warnings.html and I dont know how to combine this two types of behaviour.

+5  A: 

Looking at the code to warnings.py, you can't assign more than one filter action to a warning, and you can't (easily) define your own actions, like 'raise_once'.

However, if you want to raise a warning as an exception, but just once, that means that you are catching the exception. Why not put a line in your except clause that sets an 'ignore' action on that particular warning?

#!/usr/bin/python

import warnings

warnings.filterwarnings('error','Test')
for i in range(2):
  try:
    warnings.warn('Test');
  except UserWarning, e:
    print "Error caught"
    warnings.filterwarnings('ignore','Test')
Ian Clelland
Is there a way to make warnings mute after few similar warnings? I mean after exact number of same warnings.
L1ker