views:

87

answers:

3

Hi, I am dealing with a problem how to raise a Warning in Python without having to let the program crash / stop / interrupt.

I use following simple function that only checks if the user passed to it a non-zero number. If the user passes a zero, the program should warn the user, but continue normally. It should work like the following code, but should use class Warning(), Error() or Exception() instead of printing the warning out manually.

def isZero( i):
   if i != 0:
     print "OK"
   else:
     print "WARNING: the input is 0!"
   return i

If I use the code below and pass 0 to the function, the program crashes and the value is never returned. Instead, I want the program to continue normally and just inform the user that he passed 0 to the function.

def isZero( i):
   if i != 0:
     print "OK"
   else:
     raise Warning("the input is 0!")
   return i

The point is that I want to be able to test that a warning has been thrown testing it by unittest. If I simply print the message out, I am not able to test it with assertRaises in unittest.

Thank you, Tomas

+5  A: 

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather then warning.

SilentGhost
Thank you very much. And how then do I test that the Warning has been thrown using unittest? I cannot use assertRaises() anymore.
Tomas Novotny
@Tomas Novotny you can capture stdout and stderr, then check that the strings issued by your warning are found within.
wheaties
@Tomas: I never heard of desire to test for warning, but there is available a [`warnings.catch_warnings`](http://docs.python.org/library/warnings.html#warnings.catch_warnings) context manager that will let you do this.
SilentGhost
A: 

You can do this:

sys.stderr.write("some message")
traceback.print_exc()
James Roth
+1  A: 
import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

necromancer