Back to index

python3.2  3.2.2
Classes | Functions | Variables
warnings Namespace Reference

Classes

class  _OptionError
class  WarningMessage
class  catch_warnings

Functions

def showwarning
def formatwarning
def filterwarnings
def simplefilter
def resetwarnings
def _processoptions
def _setoption
def _getaction
def _getcategory
def warn
def warn_explicit

Variables

list __all__
 _warnings_defaults = False
 defaultaction = _defaultaction
 onceregistry = _onceregistry
list filters = []
list silence = [ImportWarning, PendingDeprecationWarning]
 bytes_warning = sys.flags.bytes_warning
string bytes_action = "error"
string resource_action = "always"

Detailed Description

Python part of the warnings subsystem.

Function Documentation

def warnings._getaction (   action) [private]

Definition at line 123 of file warnings.py.

00123 
00124 def _getaction(action):
00125     if not action:
00126         return "default"
00127     if action == "all": return "always" # Alias
00128     for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
00129         if a.startswith(action):
00130             return a
00131     raise _OptionError("invalid action: %r" % (action,))
00132 
# Helper for _setoption()

Here is the caller graph for this function:

def warnings._getcategory (   category) [private]

Definition at line 133 of file warnings.py.

00133 
00134 def _getcategory(category):
00135     import re
00136     if not category:
00137         return Warning
00138     if re.match("^[a-zA-Z0-9_]+$", category):
00139         try:
00140             cat = eval(category)
00141         except NameError:
00142             raise _OptionError("unknown warning category: %r" % (category,))
00143     else:
00144         i = category.rfind(".")
00145         module = category[:i]
00146         klass = category[i+1:]
00147         try:
00148             m = __import__(module, None, None, [klass])
00149         except ImportError:
00150             raise _OptionError("invalid module name: %r" % (module,))
00151         try:
00152             cat = getattr(m, klass)
00153         except AttributeError:
00154             raise _OptionError("unknown warning category: %r" % (category,))
00155     if not issubclass(cat, Warning):
00156         raise _OptionError("invalid warning category: %r" % (category,))
00157     return cat
00158 
00159 
# Code typically replaced by _warnings

Here is the call graph for this function:

Here is the caller graph for this function:

def warnings._processoptions (   args) [private]

Definition at line 88 of file warnings.py.

00088 
00089 def _processoptions(args):
00090     for arg in args:
00091         try:
00092             _setoption(arg)
00093         except _OptionError as msg:
00094             print("Invalid -W option ignored:", msg, file=sys.stderr)
00095 
# Helper for _processoptions()

Here is the call graph for this function:

def warnings._setoption (   arg) [private]

Definition at line 96 of file warnings.py.

00096 
00097 def _setoption(arg):
00098     import re
00099     parts = arg.split(':')
00100     if len(parts) > 5:
00101         raise _OptionError("too many fields (max 5): %r" % (arg,))
00102     while len(parts) < 5:
00103         parts.append('')
00104     action, message, category, module, lineno = [s.strip()
00105                                                  for s in parts]
00106     action = _getaction(action)
00107     message = re.escape(message)
00108     category = _getcategory(category)
00109     module = re.escape(module)
00110     if module:
00111         module = module + '$'
00112     if lineno:
00113         try:
00114             lineno = int(lineno)
00115             if lineno < 0:
00116                 raise ValueError
00117         except (ValueError, OverflowError):
00118             raise _OptionError("invalid lineno %r" % (lineno,))
00119     else:
00120         lineno = 0
00121     filterwarnings(action, message, category, module, lineno)
00122 
# Helper for _setoption()

Here is the call graph for this function:

Here is the caller graph for this function:

def warnings.filterwarnings (   action,
  message = "",
  category = Warning,
  module = "",
  lineno = 0,
  append = False 
)
Insert an entry into the list of warnings filters (at the front).

'action' -- one of "error", "ignore", "always", "default", "module",
            or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters

Definition at line 32 of file warnings.py.

00032 
00033                    append=False):
00034     """Insert an entry into the list of warnings filters (at the front).
00035 
00036     'action' -- one of "error", "ignore", "always", "default", "module",
00037                 or "once"
00038     'message' -- a regex that the warning message must match
00039     'category' -- a class that the warning must be a subclass of
00040     'module' -- a regex that the module name must match
00041     'lineno' -- an integer line number, 0 matches all warnings
00042     'append' -- if true, append to the list of filters
00043     """
00044     import re
00045     assert action in ("error", "ignore", "always", "default", "module",
00046                       "once"), "invalid action: %r" % (action,)
00047     assert isinstance(message, str), "message must be a string"
00048     assert isinstance(category, type), "category must be a class"
00049     assert issubclass(category, Warning), "category must be a Warning subclass"
00050     assert isinstance(module, str), "module must be a string"
00051     assert isinstance(lineno, int) and lineno >= 0, \
00052            "lineno must be an int >= 0"
00053     item = (action, re.compile(message, re.I), category,
00054             re.compile(module), lineno)
00055     if append:
00056         filters.append(item)
00057     else:
00058         filters.insert(0, item)

Here is the call graph for this function:

Here is the caller graph for this function:

def warnings.formatwarning (   message,
  category,
  filename,
  lineno,
  line = None 
)
Function to format a warning the standard way.

Definition at line 22 of file warnings.py.

00022 
00023 def formatwarning(message, category, filename, lineno, line=None):
00024     """Function to format a warning the standard way."""
00025     s =  "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
00026     line = linecache.getline(filename, lineno) if line is None else line
00027     if line:
00028         line = line.strip()
00029         s += "  %s\n" % line
00030     return s

Here is the call graph for this function:

Here is the caller graph for this function:

Clear the list of warning filters, so that no filters are active.

Definition at line 79 of file warnings.py.

00079 
00080 def resetwarnings():
00081     """Clear the list of warning filters, so that no filters are active."""
00082     filters[:] = []

def warnings.showwarning (   message,
  category,
  filename,
  lineno,
  file = None,
  line = None 
)
Hook to write a warning to a file; replace if you like.

Definition at line 13 of file warnings.py.

00013 
00014 def showwarning(message, category, filename, lineno, file=None, line=None):
00015     """Hook to write a warning to a file; replace if you like."""
00016     if file is None:
00017         file = sys.stderr
00018     try:
00019         file.write(formatwarning(message, category, filename, lineno, line))
00020     except IOError:
00021         pass # the file (probably stderr) is invalid - this warning gets lost.

Here is the call graph for this function:

Here is the caller graph for this function:

def warnings.simplefilter (   action,
  category = Warning,
  lineno = 0,
  append = False 
)
Insert a simple entry into the list of warnings filters (at the front).

A simple filter matches all modules and messages.
'action' -- one of "error", "ignore", "always", "default", "module",
            or "once"
'category' -- a class that the warning must be a subclass of
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters

Definition at line 59 of file warnings.py.

00059 
00060 def simplefilter(action, category=Warning, lineno=0, append=False):
00061     """Insert a simple entry into the list of warnings filters (at the front).
00062 
00063     A simple filter matches all modules and messages.
00064     'action' -- one of "error", "ignore", "always", "default", "module",
00065                 or "once"
00066     'category' -- a class that the warning must be a subclass of
00067     'lineno' -- an integer line number, 0 matches all warnings
00068     'append' -- if true, append to the list of filters
00069     """
00070     assert action in ("error", "ignore", "always", "default", "module",
00071                       "once"), "invalid action: %r" % (action,)
00072     assert isinstance(lineno, int) and lineno >= 0, \
00073            "lineno must be an int >= 0"
00074     item = (action, None, category, None, lineno)
00075     if append:
00076         filters.append(item)
00077     else:
00078         filters.insert(0, item)

Here is the caller graph for this function:

def warnings.warn (   message,
  category = None,
  stacklevel = 1 
)
Issue a warning, or maybe ignore it or raise an exception.

Definition at line 160 of file warnings.py.

00160 
00161 def warn(message, category=None, stacklevel=1):
00162     """Issue a warning, or maybe ignore it or raise an exception."""
00163     # Check if message is already a Warning object
00164     if isinstance(message, Warning):
00165         category = message.__class__
00166     # Check category argument
00167     if category is None:
00168         category = UserWarning
00169     assert issubclass(category, Warning)
00170     # Get context information
00171     try:
00172         caller = sys._getframe(stacklevel)
00173     except ValueError:
00174         globals = sys.__dict__
00175         lineno = 1
00176     else:
00177         globals = caller.f_globals
00178         lineno = caller.f_lineno
00179     if '__name__' in globals:
00180         module = globals['__name__']
00181     else:
00182         module = "<string>"
00183     filename = globals.get('__file__')
00184     if filename:
00185         fnl = filename.lower()
00186         if fnl.endswith((".pyc", ".pyo")):
00187             filename = filename[:-1]
00188     else:
00189         if module == "__main__":
00190             try:
00191                 filename = sys.argv[0]
00192             except AttributeError:
00193                 # embedded interpreters don't have sys.argv, see bug #839151
00194                 filename = '__main__'
00195         if not filename:
00196             filename = module
00197     registry = globals.setdefault("__warningregistry__", {})
00198     warn_explicit(message, category, filename, lineno, module, registry,
00199                   globals)

Here is the call graph for this function:

def warnings.warn_explicit (   message,
  category,
  filename,
  lineno,
  module = None,
  registry = None,
  module_globals = None 
)

Definition at line 201 of file warnings.py.

00201 
00202                   module=None, registry=None, module_globals=None):
00203     lineno = int(lineno)
00204     if module is None:
00205         module = filename or "<unknown>"
00206         if module[-3:].lower() == ".py":
00207             module = module[:-3] # XXX What about leading pathname?
00208     if registry is None:
00209         registry = {}
00210     if isinstance(message, Warning):
00211         text = str(message)
00212         category = message.__class__
00213     else:
00214         text = message
00215         message = category(message)
00216     key = (text, category, lineno)
00217     # Quick test for common case
00218     if registry.get(key):
00219         return
00220     # Search the filters
00221     for item in filters:
00222         action, msg, cat, mod, ln = item
00223         if ((msg is None or msg.match(text)) and
00224             issubclass(category, cat) and
00225             (mod is None or mod.match(module)) and
00226             (ln == 0 or lineno == ln)):
00227             break
00228     else:
00229         action = defaultaction
00230     # Early exit actions
00231     if action == "ignore":
00232         registry[key] = 1
00233         return
00234 
00235     # Prime the linecache for formatting, in case the
00236     # "file" is actually in a zipfile or something.
00237     linecache.getlines(filename, module_globals)
00238 
00239     if action == "error":
00240         raise message
00241     # Other actions
00242     if action == "once":
00243         registry[key] = 1
00244         oncekey = (text, category)
00245         if onceregistry.get(oncekey):
00246             return
00247         onceregistry[oncekey] = 1
00248     elif action == "always":
00249         pass
00250     elif action == "module":
00251         registry[key] = 1
00252         altkey = (text, category, 0)
00253         if registry.get(altkey):
00254             return
00255         registry[altkey] = 1
00256     elif action == "default":
00257         registry[key] = 1
00258     else:
00259         # Unrecognized actions are errors
00260         raise RuntimeError(
00261               "Unrecognized action (%r) in warnings.filters:\n %s" %
00262               (action, item))
00263     if not hasattr(showwarning, "__call__"):
00264         raise TypeError("warnings.showwarning() must be set to a "
00265                         "function or method")
00266     # Print message and context
00267     showwarning(message, category, filename, lineno)
00268 

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["warn", "showwarning", "formatwarning", "filterwarnings",
00002            "resetwarnings", "catch_warnings"]

Definition at line 9 of file warnings.py.

Definition at line 358 of file warnings.py.

Definition at line 380 of file warnings.py.

warnings.bytes_warning = sys.flags.bytes_warning

Definition at line 378 of file warnings.py.

string warnings.defaultaction = _defaultaction

Definition at line 362 of file warnings.py.

list warnings.filters = []

Definition at line 366 of file warnings.py.

Definition at line 363 of file warnings.py.

Definition at line 388 of file warnings.py.

list warnings.silence = [ImportWarning, PendingDeprecationWarning]

Definition at line 374 of file warnings.py.