Question

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.

Was it helpful?

Solution

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top