Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python2....
File: warnings.py
"""Python part of the warnings subsystem."""
[0] Fix | Delete
[1] Fix | Delete
# Note: function level imports should *not* be used
[2] Fix | Delete
# in this module as it may cause import lock deadlock.
[3] Fix | Delete
# See bug 683658.
[4] Fix | Delete
import linecache
[5] Fix | Delete
import sys
[6] Fix | Delete
import types
[7] Fix | Delete
[8] Fix | Delete
__all__ = ["warn", "warn_explicit", "showwarning",
[9] Fix | Delete
"formatwarning", "filterwarnings", "simplefilter",
[10] Fix | Delete
"resetwarnings", "catch_warnings"]
[11] Fix | Delete
[12] Fix | Delete
[13] Fix | Delete
def warnpy3k(message, category=None, stacklevel=1):
[14] Fix | Delete
"""Issue a deprecation warning for Python 3.x related changes.
[15] Fix | Delete
[16] Fix | Delete
Warnings are omitted unless Python is started with the -3 option.
[17] Fix | Delete
"""
[18] Fix | Delete
if sys.py3kwarning:
[19] Fix | Delete
if category is None:
[20] Fix | Delete
category = DeprecationWarning
[21] Fix | Delete
warn(message, category, stacklevel+1)
[22] Fix | Delete
[23] Fix | Delete
def _show_warning(message, category, filename, lineno, file=None, line=None):
[24] Fix | Delete
"""Hook to write a warning to a file; replace if you like."""
[25] Fix | Delete
if file is None:
[26] Fix | Delete
file = sys.stderr
[27] Fix | Delete
if file is None:
[28] Fix | Delete
# sys.stderr is None - warnings get lost
[29] Fix | Delete
return
[30] Fix | Delete
try:
[31] Fix | Delete
file.write(formatwarning(message, category, filename, lineno, line))
[32] Fix | Delete
except (IOError, UnicodeError):
[33] Fix | Delete
pass # the file (probably stderr) is invalid - this warning gets lost.
[34] Fix | Delete
# Keep a working version around in case the deprecation of the old API is
[35] Fix | Delete
# triggered.
[36] Fix | Delete
showwarning = _show_warning
[37] Fix | Delete
[38] Fix | Delete
def formatwarning(message, category, filename, lineno, line=None):
[39] Fix | Delete
"""Function to format a warning the standard way."""
[40] Fix | Delete
try:
[41] Fix | Delete
unicodetype = unicode
[42] Fix | Delete
except NameError:
[43] Fix | Delete
unicodetype = ()
[44] Fix | Delete
try:
[45] Fix | Delete
message = str(message)
[46] Fix | Delete
except UnicodeEncodeError:
[47] Fix | Delete
pass
[48] Fix | Delete
s = "%s: %s: %s\n" % (lineno, category.__name__, message)
[49] Fix | Delete
line = linecache.getline(filename, lineno) if line is None else line
[50] Fix | Delete
if line:
[51] Fix | Delete
line = line.strip()
[52] Fix | Delete
if isinstance(s, unicodetype) and isinstance(line, str):
[53] Fix | Delete
line = unicode(line, 'latin1')
[54] Fix | Delete
s += " %s\n" % line
[55] Fix | Delete
if isinstance(s, unicodetype) and isinstance(filename, str):
[56] Fix | Delete
enc = sys.getfilesystemencoding()
[57] Fix | Delete
if enc:
[58] Fix | Delete
try:
[59] Fix | Delete
filename = unicode(filename, enc)
[60] Fix | Delete
except UnicodeDecodeError:
[61] Fix | Delete
pass
[62] Fix | Delete
s = "%s:%s" % (filename, s)
[63] Fix | Delete
return s
[64] Fix | Delete
[65] Fix | Delete
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
[66] Fix | Delete
append=0):
[67] Fix | Delete
"""Insert an entry into the list of warnings filters (at the front).
[68] Fix | Delete
[69] Fix | Delete
'action' -- one of "error", "ignore", "always", "default", "module",
[70] Fix | Delete
or "once"
[71] Fix | Delete
'message' -- a regex that the warning message must match
[72] Fix | Delete
'category' -- a class that the warning must be a subclass of
[73] Fix | Delete
'module' -- a regex that the module name must match
[74] Fix | Delete
'lineno' -- an integer line number, 0 matches all warnings
[75] Fix | Delete
'append' -- if true, append to the list of filters
[76] Fix | Delete
"""
[77] Fix | Delete
import re
[78] Fix | Delete
assert action in ("error", "ignore", "always", "default", "module",
[79] Fix | Delete
"once"), "invalid action: %r" % (action,)
[80] Fix | Delete
assert isinstance(message, basestring), "message must be a string"
[81] Fix | Delete
assert isinstance(category, (type, types.ClassType)), \
[82] Fix | Delete
"category must be a class"
[83] Fix | Delete
assert issubclass(category, Warning), "category must be a Warning subclass"
[84] Fix | Delete
assert isinstance(module, basestring), "module must be a string"
[85] Fix | Delete
assert isinstance(lineno, int) and lineno >= 0, \
[86] Fix | Delete
"lineno must be an int >= 0"
[87] Fix | Delete
item = (action, re.compile(message, re.I), category,
[88] Fix | Delete
re.compile(module), lineno)
[89] Fix | Delete
if append:
[90] Fix | Delete
filters.append(item)
[91] Fix | Delete
else:
[92] Fix | Delete
filters.insert(0, item)
[93] Fix | Delete
[94] Fix | Delete
def simplefilter(action, category=Warning, lineno=0, append=0):
[95] Fix | Delete
"""Insert a simple entry into the list of warnings filters (at the front).
[96] Fix | Delete
[97] Fix | Delete
A simple filter matches all modules and messages.
[98] Fix | Delete
'action' -- one of "error", "ignore", "always", "default", "module",
[99] Fix | Delete
or "once"
[100] Fix | Delete
'category' -- a class that the warning must be a subclass of
[101] Fix | Delete
'lineno' -- an integer line number, 0 matches all warnings
[102] Fix | Delete
'append' -- if true, append to the list of filters
[103] Fix | Delete
"""
[104] Fix | Delete
assert action in ("error", "ignore", "always", "default", "module",
[105] Fix | Delete
"once"), "invalid action: %r" % (action,)
[106] Fix | Delete
assert isinstance(lineno, int) and lineno >= 0, \
[107] Fix | Delete
"lineno must be an int >= 0"
[108] Fix | Delete
item = (action, None, category, None, lineno)
[109] Fix | Delete
if append:
[110] Fix | Delete
filters.append(item)
[111] Fix | Delete
else:
[112] Fix | Delete
filters.insert(0, item)
[113] Fix | Delete
[114] Fix | Delete
def resetwarnings():
[115] Fix | Delete
"""Clear the list of warning filters, so that no filters are active."""
[116] Fix | Delete
filters[:] = []
[117] Fix | Delete
[118] Fix | Delete
class _OptionError(Exception):
[119] Fix | Delete
"""Exception used by option processing helpers."""
[120] Fix | Delete
pass
[121] Fix | Delete
[122] Fix | Delete
# Helper to process -W options passed via sys.warnoptions
[123] Fix | Delete
def _processoptions(args):
[124] Fix | Delete
for arg in args:
[125] Fix | Delete
try:
[126] Fix | Delete
_setoption(arg)
[127] Fix | Delete
except _OptionError, msg:
[128] Fix | Delete
print >>sys.stderr, "Invalid -W option ignored:", msg
[129] Fix | Delete
[130] Fix | Delete
# Helper for _processoptions()
[131] Fix | Delete
def _setoption(arg):
[132] Fix | Delete
import re
[133] Fix | Delete
parts = arg.split(':')
[134] Fix | Delete
if len(parts) > 5:
[135] Fix | Delete
raise _OptionError("too many fields (max 5): %r" % (arg,))
[136] Fix | Delete
while len(parts) < 5:
[137] Fix | Delete
parts.append('')
[138] Fix | Delete
action, message, category, module, lineno = [s.strip()
[139] Fix | Delete
for s in parts]
[140] Fix | Delete
action = _getaction(action)
[141] Fix | Delete
message = re.escape(message)
[142] Fix | Delete
category = _getcategory(category)
[143] Fix | Delete
module = re.escape(module)
[144] Fix | Delete
if module:
[145] Fix | Delete
module = module + '$'
[146] Fix | Delete
if lineno:
[147] Fix | Delete
try:
[148] Fix | Delete
lineno = int(lineno)
[149] Fix | Delete
if lineno < 0:
[150] Fix | Delete
raise ValueError
[151] Fix | Delete
except (ValueError, OverflowError):
[152] Fix | Delete
raise _OptionError("invalid lineno %r" % (lineno,))
[153] Fix | Delete
else:
[154] Fix | Delete
lineno = 0
[155] Fix | Delete
filterwarnings(action, message, category, module, lineno)
[156] Fix | Delete
[157] Fix | Delete
# Helper for _setoption()
[158] Fix | Delete
def _getaction(action):
[159] Fix | Delete
if not action:
[160] Fix | Delete
return "default"
[161] Fix | Delete
if action == "all": return "always" # Alias
[162] Fix | Delete
for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
[163] Fix | Delete
if a.startswith(action):
[164] Fix | Delete
return a
[165] Fix | Delete
raise _OptionError("invalid action: %r" % (action,))
[166] Fix | Delete
[167] Fix | Delete
# Helper for _setoption()
[168] Fix | Delete
def _getcategory(category):
[169] Fix | Delete
import re
[170] Fix | Delete
if not category:
[171] Fix | Delete
return Warning
[172] Fix | Delete
if re.match("^[a-zA-Z0-9_]+$", category):
[173] Fix | Delete
try:
[174] Fix | Delete
cat = eval(category)
[175] Fix | Delete
except NameError:
[176] Fix | Delete
raise _OptionError("unknown warning category: %r" % (category,))
[177] Fix | Delete
else:
[178] Fix | Delete
i = category.rfind(".")
[179] Fix | Delete
module = category[:i]
[180] Fix | Delete
klass = category[i+1:]
[181] Fix | Delete
try:
[182] Fix | Delete
m = __import__(module, None, None, [klass])
[183] Fix | Delete
except ImportError:
[184] Fix | Delete
raise _OptionError("invalid module name: %r" % (module,))
[185] Fix | Delete
try:
[186] Fix | Delete
cat = getattr(m, klass)
[187] Fix | Delete
except AttributeError:
[188] Fix | Delete
raise _OptionError("unknown warning category: %r" % (category,))
[189] Fix | Delete
if not issubclass(cat, Warning):
[190] Fix | Delete
raise _OptionError("invalid warning category: %r" % (category,))
[191] Fix | Delete
return cat
[192] Fix | Delete
[193] Fix | Delete
[194] Fix | Delete
# Code typically replaced by _warnings
[195] Fix | Delete
def warn(message, category=None, stacklevel=1):
[196] Fix | Delete
"""Issue a warning, or maybe ignore it or raise an exception."""
[197] Fix | Delete
# Check if message is already a Warning object
[198] Fix | Delete
if isinstance(message, Warning):
[199] Fix | Delete
category = message.__class__
[200] Fix | Delete
# Check category argument
[201] Fix | Delete
if category is None:
[202] Fix | Delete
category = UserWarning
[203] Fix | Delete
assert issubclass(category, Warning)
[204] Fix | Delete
# Get context information
[205] Fix | Delete
try:
[206] Fix | Delete
caller = sys._getframe(stacklevel)
[207] Fix | Delete
except ValueError:
[208] Fix | Delete
globals = sys.__dict__
[209] Fix | Delete
lineno = 1
[210] Fix | Delete
else:
[211] Fix | Delete
globals = caller.f_globals
[212] Fix | Delete
lineno = caller.f_lineno
[213] Fix | Delete
if '__name__' in globals:
[214] Fix | Delete
module = globals['__name__']
[215] Fix | Delete
else:
[216] Fix | Delete
module = "<string>"
[217] Fix | Delete
filename = globals.get('__file__')
[218] Fix | Delete
if filename:
[219] Fix | Delete
fnl = filename.lower()
[220] Fix | Delete
if fnl.endswith((".pyc", ".pyo")):
[221] Fix | Delete
filename = filename[:-1]
[222] Fix | Delete
else:
[223] Fix | Delete
if module == "__main__":
[224] Fix | Delete
try:
[225] Fix | Delete
filename = sys.argv[0]
[226] Fix | Delete
except AttributeError:
[227] Fix | Delete
# embedded interpreters don't have sys.argv, see bug #839151
[228] Fix | Delete
filename = '__main__'
[229] Fix | Delete
if not filename:
[230] Fix | Delete
filename = module
[231] Fix | Delete
registry = globals.setdefault("__warningregistry__", {})
[232] Fix | Delete
warn_explicit(message, category, filename, lineno, module, registry,
[233] Fix | Delete
globals)
[234] Fix | Delete
[235] Fix | Delete
def warn_explicit(message, category, filename, lineno,
[236] Fix | Delete
module=None, registry=None, module_globals=None):
[237] Fix | Delete
lineno = int(lineno)
[238] Fix | Delete
if module is None:
[239] Fix | Delete
module = filename or "<unknown>"
[240] Fix | Delete
if module[-3:].lower() == ".py":
[241] Fix | Delete
module = module[:-3] # XXX What about leading pathname?
[242] Fix | Delete
if registry is None:
[243] Fix | Delete
registry = {}
[244] Fix | Delete
if isinstance(message, Warning):
[245] Fix | Delete
text = str(message)
[246] Fix | Delete
category = message.__class__
[247] Fix | Delete
else:
[248] Fix | Delete
text = message
[249] Fix | Delete
message = category(message)
[250] Fix | Delete
key = (text, category, lineno)
[251] Fix | Delete
# Quick test for common case
[252] Fix | Delete
if registry.get(key):
[253] Fix | Delete
return
[254] Fix | Delete
# Search the filters
[255] Fix | Delete
for item in filters:
[256] Fix | Delete
action, msg, cat, mod, ln = item
[257] Fix | Delete
if ((msg is None or msg.match(text)) and
[258] Fix | Delete
issubclass(category, cat) and
[259] Fix | Delete
(mod is None or mod.match(module)) and
[260] Fix | Delete
(ln == 0 or lineno == ln)):
[261] Fix | Delete
break
[262] Fix | Delete
else:
[263] Fix | Delete
action = defaultaction
[264] Fix | Delete
# Early exit actions
[265] Fix | Delete
if action == "ignore":
[266] Fix | Delete
registry[key] = 1
[267] Fix | Delete
return
[268] Fix | Delete
[269] Fix | Delete
# Prime the linecache for formatting, in case the
[270] Fix | Delete
# "file" is actually in a zipfile or something.
[271] Fix | Delete
linecache.getlines(filename, module_globals)
[272] Fix | Delete
[273] Fix | Delete
if action == "error":
[274] Fix | Delete
raise message
[275] Fix | Delete
# Other actions
[276] Fix | Delete
if action == "once":
[277] Fix | Delete
registry[key] = 1
[278] Fix | Delete
oncekey = (text, category)
[279] Fix | Delete
if onceregistry.get(oncekey):
[280] Fix | Delete
return
[281] Fix | Delete
onceregistry[oncekey] = 1
[282] Fix | Delete
elif action == "always":
[283] Fix | Delete
pass
[284] Fix | Delete
elif action == "module":
[285] Fix | Delete
registry[key] = 1
[286] Fix | Delete
altkey = (text, category, 0)
[287] Fix | Delete
if registry.get(altkey):
[288] Fix | Delete
return
[289] Fix | Delete
registry[altkey] = 1
[290] Fix | Delete
elif action == "default":
[291] Fix | Delete
registry[key] = 1
[292] Fix | Delete
else:
[293] Fix | Delete
# Unrecognized actions are errors
[294] Fix | Delete
raise RuntimeError(
[295] Fix | Delete
"Unrecognized action (%r) in warnings.filters:\n %s" %
[296] Fix | Delete
(action, item))
[297] Fix | Delete
# Print message and context
[298] Fix | Delete
showwarning(message, category, filename, lineno)
[299] Fix | Delete
[300] Fix | Delete
[301] Fix | Delete
class WarningMessage(object):
[302] Fix | Delete
[303] Fix | Delete
"""Holds the result of a single showwarning() call."""
[304] Fix | Delete
[305] Fix | Delete
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
[306] Fix | Delete
"line")
[307] Fix | Delete
[308] Fix | Delete
def __init__(self, message, category, filename, lineno, file=None,
[309] Fix | Delete
line=None):
[310] Fix | Delete
local_values = locals()
[311] Fix | Delete
for attr in self._WARNING_DETAILS:
[312] Fix | Delete
setattr(self, attr, local_values[attr])
[313] Fix | Delete
self._category_name = category.__name__ if category else None
[314] Fix | Delete
[315] Fix | Delete
def __str__(self):
[316] Fix | Delete
return ("{message : %r, category : %r, filename : %r, lineno : %s, "
[317] Fix | Delete
"line : %r}" % (self.message, self._category_name,
[318] Fix | Delete
self.filename, self.lineno, self.line))
[319] Fix | Delete
[320] Fix | Delete
[321] Fix | Delete
class catch_warnings(object):
[322] Fix | Delete
[323] Fix | Delete
"""A context manager that copies and restores the warnings filter upon
[324] Fix | Delete
exiting the context.
[325] Fix | Delete
[326] Fix | Delete
The 'record' argument specifies whether warnings should be captured by a
[327] Fix | Delete
custom implementation of warnings.showwarning() and be appended to a list
[328] Fix | Delete
returned by the context manager. Otherwise None is returned by the context
[329] Fix | Delete
manager. The objects appended to the list are arguments whose attributes
[330] Fix | Delete
mirror the arguments to showwarning().
[331] Fix | Delete
[332] Fix | Delete
The 'module' argument is to specify an alternative module to the module
[333] Fix | Delete
named 'warnings' and imported under that name. This argument is only useful
[334] Fix | Delete
when testing the warnings module itself.
[335] Fix | Delete
[336] Fix | Delete
"""
[337] Fix | Delete
[338] Fix | Delete
def __init__(self, record=False, module=None):
[339] Fix | Delete
"""Specify whether to record warnings and if an alternative module
[340] Fix | Delete
should be used other than sys.modules['warnings'].
[341] Fix | Delete
[342] Fix | Delete
For compatibility with Python 3.0, please consider all arguments to be
[343] Fix | Delete
keyword-only.
[344] Fix | Delete
[345] Fix | Delete
"""
[346] Fix | Delete
self._record = record
[347] Fix | Delete
self._module = sys.modules['warnings'] if module is None else module
[348] Fix | Delete
self._entered = False
[349] Fix | Delete
[350] Fix | Delete
def __repr__(self):
[351] Fix | Delete
args = []
[352] Fix | Delete
if self._record:
[353] Fix | Delete
args.append("record=True")
[354] Fix | Delete
if self._module is not sys.modules['warnings']:
[355] Fix | Delete
args.append("module=%r" % self._module)
[356] Fix | Delete
name = type(self).__name__
[357] Fix | Delete
return "%s(%s)" % (name, ", ".join(args))
[358] Fix | Delete
[359] Fix | Delete
def __enter__(self):
[360] Fix | Delete
if self._entered:
[361] Fix | Delete
raise RuntimeError("Cannot enter %r twice" % self)
[362] Fix | Delete
self._entered = True
[363] Fix | Delete
self._filters = self._module.filters
[364] Fix | Delete
self._module.filters = self._filters[:]
[365] Fix | Delete
self._showwarning = self._module.showwarning
[366] Fix | Delete
if self._record:
[367] Fix | Delete
log = []
[368] Fix | Delete
def showwarning(*args, **kwargs):
[369] Fix | Delete
log.append(WarningMessage(*args, **kwargs))
[370] Fix | Delete
self._module.showwarning = showwarning
[371] Fix | Delete
return log
[372] Fix | Delete
else:
[373] Fix | Delete
return None
[374] Fix | Delete
[375] Fix | Delete
def __exit__(self, *exc_info):
[376] Fix | Delete
if not self._entered:
[377] Fix | Delete
raise RuntimeError("Cannot exit %r without entering first" % self)
[378] Fix | Delete
self._module.filters = self._filters
[379] Fix | Delete
self._module.showwarning = self._showwarning
[380] Fix | Delete
[381] Fix | Delete
[382] Fix | Delete
# filters contains a sequence of filter 5-tuples
[383] Fix | Delete
# The components of the 5-tuple are:
[384] Fix | Delete
# - an action: error, ignore, always, default, module, or once
[385] Fix | Delete
# - a compiled regex that must match the warning message
[386] Fix | Delete
# - a class representing the warning category
[387] Fix | Delete
# - a compiled regex that must match the module that is being warned
[388] Fix | Delete
# - a line number for the line being warning, or 0 to mean any line
[389] Fix | Delete
# If either if the compiled regexs are None, match anything.
[390] Fix | Delete
_warnings_defaults = False
[391] Fix | Delete
try:
[392] Fix | Delete
from _warnings import (filters, default_action, once_registry,
[393] Fix | Delete
warn, warn_explicit)
[394] Fix | Delete
defaultaction = default_action
[395] Fix | Delete
onceregistry = once_registry
[396] Fix | Delete
_warnings_defaults = True
[397] Fix | Delete
except ImportError:
[398] Fix | Delete
filters = []
[399] Fix | Delete
defaultaction = "default"
[400] Fix | Delete
onceregistry = {}
[401] Fix | Delete
[402] Fix | Delete
[403] Fix | Delete
# Module initialization
[404] Fix | Delete
_processoptions(sys.warnoptions)
[405] Fix | Delete
if not _warnings_defaults:
[406] Fix | Delete
silence = [ImportWarning, PendingDeprecationWarning]
[407] Fix | Delete
# Don't silence DeprecationWarning if -3 or -Q was used.
[408] Fix | Delete
if not sys.py3kwarning and not sys.flags.division_warning:
[409] Fix | Delete
silence.append(DeprecationWarning)
[410] Fix | Delete
for cls in silence:
[411] Fix | Delete
simplefilter("ignore", category=cls)
[412] Fix | Delete
bytes_warning = sys.flags.bytes_warning
[413] Fix | Delete
if bytes_warning > 1:
[414] Fix | Delete
bytes_action = "error"
[415] Fix | Delete
elif bytes_warning:
[416] Fix | Delete
bytes_action = "default"
[417] Fix | Delete
else:
[418] Fix | Delete
bytes_action = "ignore"
[419] Fix | Delete
simplefilter(bytes_action, category=BytesWarning, append=1)
[420] Fix | Delete
del _warnings_defaults
[421] Fix | Delete
[422] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function