How to Raise a Warning in Python

Python programming, as a fully functional programming language suitable for desktop and Web development, contains the ability to raise exceptions when errors occur. Exceptions happen when dangerous or nonstandard behavior occurs, terminating the program. Programmers may want to raise a warning to the user in case of a nonfatal discrepancy, such as the implementation of deprecated code. In this case, a "warning" can be used to signal this fact without halting execution.

Things You'll Need

  • Python Interpreter with Interactive Development Environment
Show More

Instructions

    • 1

      Import the "warnings" library into the Python environment. The warnings library contains the methods used to raise different warnings. Warnings are helpful if the programmer wishes to notify users of a future deprecation of functionality, or changes in syntax. The following code imports the warnings library.

      >>>import warnings

    • 2

      Crete a "UserWarning" in the Python environment. Programmers can call warnings using the "warn()" method from the warnings library, which takes a string representing a warning message and the type of warning as its arguments.

      >>>warnings.warn('This is a Warning', UserWarning)

      __main__:1: UserWarning: This is a Warning

    • 3

      Create a Future Warning. This warning serves a different category. It notifies the user that a function or construct in the program will soon be changed or obsolete. This way, a programmer using the construct will know to start developing code using the new constructs, or prepare to convert older code to the new construct. This example shows a warning raised when a programmer calls a object that will soon be changed.

      >>>a = OldObject()

      >>>if isinstance(a, OldObject)

      . . . warnings.warn("Object will soon undergo the following changes...", FutureWarning)

Related Searches:

References

Comments

Related Ads

Featured