Generating warnings

warn() is used to generate the warnings. Now, we will see a simple example of generating warnings. Write a script called generate_warnings.py and write a following code in it:

import warnings
warnings.simplefilter('error', UserWarning)
print('Before')
warnings.warn('Write your warning message here')
print('After')

Run the script as follows:

$ python3 generate_warnings.py

Output:
Before:
Traceback (most recent call last):
File "generate_warnings.py", line 6, in <module>
warnings.warn('Write your warning message here')
UserWarning: Write your warning message here

In the preceding script, we passed a warning message through warn(). We used a simple filter so that your warning will get treated as an error and that error will get solved accordingly by the programmer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset