cinap_lenrekadd hg and python4bb9e2215 years agoHistory
253 lines · 10.2 KB · TeX
RawDownload
\section{\module{warnings} ---         Warning control} \declaremodule{standard}{warnings}\modulesynopsis{Issue warning messages and control their disposition.}\index{warnings} \versionadded{2.1} Warning messages are typically issued in situations where it is usefulto alert the user of some condition in a program, where that condition(normally) doesn't warrant raising an exception and terminating theprogram.  For example, one might want to issue a warning when aprogram uses an obsolete module. Python programmers issue warnings by calling the \function{warn()}function defined in this module.  (C programmers use\cfunction{PyErr_Warn()}; see the\citetitle[../api/exceptionHandling.html]{Python/C API ReferenceManual} for details). Warning messages are normally written to \code{sys.stderr}, but theirdisposition can be changed flexibly, from ignoring all warnings toturning them into exceptions.  The disposition of warnings can varybased on the warning category (see below), the text of the warningmessage, and the source location where it is issued.  Repetitions of aparticular warning for the same source location are typicallysuppressed. There are two stages in warning control: first, each time a warning isissued, a determination is made whether a message should be issued ornot; next, if a message is to be issued, it is formatted and printedusing a user-settable hook. The determination whether to issue a warning message is controlled bythe warning filter, which is a sequence of matching rules and actions.Rules can be added to the filter by calling\function{filterwarnings()} and reset to its default state by calling\function{resetwarnings()}. The printing of warning messages is done by calling\function{showwarning()}, which may be overridden; the defaultimplementation of this function formats the message by calling\function{formatwarning()}, which is also available for use by customimplementations.  \subsection{Warning Categories \label{warning-categories}} There are a number of built-in exceptions that represent warningcategories.  This categorization is useful to be able to filter outgroups of warnings.  The following warnings category classes arecurrently defined: \begin{tableii}{l|l}{exception}{Class}{Description} \lineii{Warning}{This is the base class of all warning categoryclasses.  It is a subclass of \exception{Exception}.} \lineii{UserWarning}{The default category for \function{warn()}.} \lineii{DeprecationWarning}{Base category for warnings aboutdeprecated features.} \lineii{SyntaxWarning}{Base category for warnings about dubioussyntactic features.} \lineii{RuntimeWarning}{Base category for warnings about dubiousruntime features.} \lineii{FutureWarning}{Base category for warnings about constructsthat will change semantically in the future.} \lineii{PendingDeprecationWarning}{Base category for warnings aboutfeatures that will be deprecated in the future (ignored by default).} \lineii{ImportWarning}{Base category for warnings triggered during theprocess of importing a module (ignored by default).} \lineii{UnicodeWarning}{Base category for warnings related to Unicode.} \end{tableii} While these are technically built-in exceptions, they are documentedhere, because conceptually they belong to the warnings mechanism. User code can define additional warning categories by subclassing oneof the standard warning categories.  A warning category must always bea subclass of the \exception{Warning} class.  \subsection{The Warnings Filter \label{warning-filter}} The warnings filter controls whether warnings are ignored, displayed,or turned into errors (raising an exception). Conceptually, the warnings filter maintains an ordered list of filterspecifications; any specific warning is matched against each filterspecification in the list in turn until a match is found; the matchdetermines the disposition of the match.  Each entry is a tuple of theform (\var{action}, \var{message}, \var{category}, \var{module},\var{lineno}), where: \begin{itemize} \item \var{action} is one of the following strings:     \begin{tableii}{l|l}{code}{Value}{Disposition}     \lineii{"error"}{turn matching warnings into exceptions}     \lineii{"ignore"}{never print matching warnings}     \lineii{"always"}{always print matching warnings}     \lineii{"default"}{print the first occurrence of matching    warnings for each location where the warning is issued}     \lineii{"module"}{print the first occurrence of matching    warnings for each module where the warning is issued}     \lineii{"once"}{print only the first occurrence of matching    warnings, regardless of location}     \end{tableii} \item \var{message} is a string containing a regular expression thatthe warning message must match (the match is compiled to always be case-insensitive)  \item \var{category} is a class (a subclass of \exception{Warning}) of      which the warning category must be a subclass in order to match \item \var{module} is a string containing a regular expression that the module      name must match (the match is compiled to be case-sensitive) \item \var{lineno} is an integer that the line number where the      warning occurred must match, or \code{0} to match all line      numbers \end{itemize} Since the \exception{Warning} class is derived from the built-in\exception{Exception} class, to turn a warning into an error we simplyraise \code{category(message)}. The warnings filter is initialized by \programopt{-W} options passedto the Python interpreter command line.  The interpreter saves thearguments for all \programopt{-W} options without interpretation in\code{sys.warnoptions}; the \module{warnings} module parses these whenit is first imported (invalid options are ignored, after printing amessage to \code{sys.stderr}). The warnings that are ignored by default may be enabled by passing \programopt{-Wd} to the interpreter. This enables default handlingfor all warnings, including those that are normally ignored bydefault. This is particular useful for enabling ImportWarning whendebugging problems importing a developed package. ImportWarning canalso be enabled explicitly in Python code using: \begin{verbatim}    warnings.simplefilter('default', ImportWarning)\end{verbatim}  \subsection{Available Functions \label{warning-functions}} \begin{funcdesc}{warn}{message\optional{, category\optional{, stacklevel}}}Issue a warning, or maybe ignore it or raise an exception.  The\var{category} argument, if given, must be a warning category class(see above); it defaults to \exception{UserWarning}.  Alternatively\var{message} can be a \exception{Warning} instance, in which case\var{category} will be ignored and \code{message.__class__} will be used.In this case the message text will be \code{str(message)}. This functionraises an exception if the particular warning issued is changedinto an error by the warnings filter see above.  The \var{stacklevel}argument can be used by wrapper functions written in Python, likethis: \begin{verbatim}def deprecation(message):    warnings.warn(message, DeprecationWarning, stacklevel=2)\end{verbatim} This makes the warning refer to \function{deprecation()}'s caller,rather than to the source of \function{deprecation()} itself (sincethe latter would defeat the purpose of the warning message).\end{funcdesc} \begin{funcdesc}{warn_explicit}{message, category, filename, lineno\optional{, module\optional{, registry\optional{, module_globals}}}}This is a low-level interface to the functionality of\function{warn()}, passing in explicitly the message, category,filename and line number, and optionally the module name and theregistry (which should be the \code{__warningregistry__} dictionary ofthe module).  The module name defaults to the filename with \code{.py}stripped; if no registry is passed, the warning is never suppressed.\var{message} must be a string and \var{category} a subclass of\exception{Warning} or \var{message} may be a \exception{Warning} instance,in which case \var{category} will be ignored. \var{module_globals}, if supplied, should be the global namespace in useby the code for which the warning is issued.  (This argument is used tosupport displaying source for modules found in zipfiles or othernon-filesystem import sources, and was added in Python 2.5.)\end{funcdesc} \begin{funcdesc}{showwarning}{message, category, filename,			     lineno\optional{, file}}Write a warning to a file.  The default implementation calls\code{formatwarning(\var{message}, \var{category}, \var{filename},\var{lineno})} and writes the resulting string to \var{file}, whichdefaults to \code{sys.stderr}.  You may replace this function with analternative implementation by assigning to\code{warnings.showwarning}.\end{funcdesc} \begin{funcdesc}{formatwarning}{message, category, filename, lineno}Format a warning the standard way.  This returns a string  which maycontain embedded newlines and ends in a newline.\end{funcdesc} \begin{funcdesc}{filterwarnings}{action\optional{,                 message\optional{, category\optional{,                 module\optional{, lineno\optional{, append}}}}}}Insert an entry into the list of warnings filters.  The entry isinserted at the front by default; if \var{append} is true, it isinserted at the end.This checks the types of the arguments, compiles the message andmodule regular expressions, and inserts them as a tuple in the list of warnings filters.  Entries closer to the front of the listoverride entries later in the list, if both match a particularwarning.  Omitted arguments default to a value that matcheseverything.\end{funcdesc} \begin{funcdesc}{simplefilter}{action\optional{,                 category\optional{,                 lineno\optional{, append}}}}Insert a simple entry into the list of warnings filters. The meaningof the function parameters is as for \function{filterwarnings()}, butregular expressions are not needed as the filter inserted alwaysmatches any message in any module as long as the category and linenumber match.\end{funcdesc} \begin{funcdesc}{resetwarnings}{}Reset the warnings filter.  This discards the effect of all previouscalls to \function{filterwarnings()}, including that of the\programopt{-W} command line options and calls to\function{simplefilter()}.\end{funcdesc}