Problem - To have a program that can issue warning messages (e.g., about deprecated features or usage problems).
Code #1 : Use the warnings.warn() function
The arguments to
warn() are a warning message along with a warning class, which is typically one of the following: UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, or FutureWarning.
The handling of warnings depends on how the interpreter is executed and other configuration. If Python with the
-W all option is run, the following output is obtained:
bash % python3 -W all example.py
example.py:5: DeprecationWarning: logfile argument is deprecated
warnings.warn('logfile argument is deprecated', DeprecationWarning)
Normally, warnings just produce output messages on standard error. To turn warnings into exceptions, use the
-W error option.
Code #2 :
bash % python3 -W error example.py
Traceback (most recent call last):
File "example.py", line 10, in
Issuing a warning message is often a useful technique for maintaining software and assisting users with issues that don’t necessarily rise to the level of being a full-fledged exception.
Code #3 : Warning message generated by destroying a file without closing it.