1.

How are warnings generated in Python?

Answer»

Exceptions are generally fatal as the program TERMINATES instantly when an unhandled exception occurs. Warnings are non-fatal. A warning message is displayed but the program won’t terminate. Warnings generally appear if some deprecated usage of CERTAIN programming element like keyword/function/class etc. occurs.

Python’s builtins module defines Warnings class which is inherited from Exception itself. However, custom warning messages can be displayed with the help of WARN() function defined in built-in warnings module.

There are a number of built-in Warning subclasses. User defined subclass can also be defined.

WarningThis is the base class of all warning category classes
UserWarningThe default category for warn().
DeprecationWarningWarnings about deprecated features when those warnings are intended for developers
SyntaxWarningWarnings about dubious syntactic features
RuntimeWarningWarnings about dubious runtime features
FutureWarningWarnings about deprecated features when those warnings are intended for end users
PendingDeprecationWarningWarnings about features that will be deprecated in the future
ImportWarningWarnings triggered during the process of importing a module
UnicodeWarningWarnings related to Unicode
BytesWarningWarnings related to bytes and bytearray
ResourceWarningWarnings related to resource usage

Following code defines WarnExample class. When method1() is called, it issues a depreciation warning.

# warningexample.py  import warnings class WarnExample:     def __init__(self):         self.text = "Warning"     def method1(self):         warnings.warn(             "method1 is deprecated, USE new_method INSTEAD",             DeprecationWarning if __name__=='__main__':                 e=WarnExample()         e.method1()

Output:

$ python -Wd warningexample.py warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead   DeprecationWarning


Discussion

No Comment Found