I use the following simple function to check if the user passed a non-zero number to it. If so, the program should warn them, but continue as per normal. It should work like the code below, but should use class Warning() , Error() or Exception() instead of printing the warning out manually.
showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file. simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.
Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library.
import warnings
warnings.warn("Warning...........Message")
See the python documentation: here
You shouldn't raise
the warning, you should be using warnings
module. By raising it you're generating error, rather than warning.
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With