1 | n/a | """Python part of the warnings subsystem.""" |
---|
2 | n/a | |
---|
3 | n/a | import sys |
---|
4 | n/a | |
---|
5 | n/a | |
---|
6 | n/a | __all__ = ["warn", "warn_explicit", "showwarning", |
---|
7 | n/a | "formatwarning", "filterwarnings", "simplefilter", |
---|
8 | n/a | "resetwarnings", "catch_warnings"] |
---|
9 | n/a | |
---|
10 | n/a | def showwarning(message, category, filename, lineno, file=None, line=None): |
---|
11 | n/a | """Hook to write a warning to a file; replace if you like.""" |
---|
12 | n/a | msg = WarningMessage(message, category, filename, lineno, file, line) |
---|
13 | n/a | _showwarnmsg_impl(msg) |
---|
14 | n/a | |
---|
15 | n/a | def formatwarning(message, category, filename, lineno, line=None): |
---|
16 | n/a | """Function to format a warning the standard way.""" |
---|
17 | n/a | msg = WarningMessage(message, category, filename, lineno, None, line) |
---|
18 | n/a | return _formatwarnmsg_impl(msg) |
---|
19 | n/a | |
---|
20 | n/a | def _showwarnmsg_impl(msg): |
---|
21 | n/a | file = msg.file |
---|
22 | n/a | if file is None: |
---|
23 | n/a | file = sys.stderr |
---|
24 | n/a | if file is None: |
---|
25 | n/a | # sys.stderr is None when run with pythonw.exe: |
---|
26 | n/a | # warnings get lost |
---|
27 | n/a | return |
---|
28 | n/a | text = _formatwarnmsg(msg) |
---|
29 | n/a | try: |
---|
30 | n/a | file.write(text) |
---|
31 | n/a | except OSError: |
---|
32 | n/a | # the file (probably stderr) is invalid - this warning gets lost. |
---|
33 | n/a | pass |
---|
34 | n/a | |
---|
35 | n/a | def _formatwarnmsg_impl(msg): |
---|
36 | n/a | s = ("%s:%s: %s: %s\n" |
---|
37 | n/a | % (msg.filename, msg.lineno, msg.category.__name__, |
---|
38 | n/a | msg.message)) |
---|
39 | n/a | |
---|
40 | n/a | if msg.line is None: |
---|
41 | n/a | try: |
---|
42 | n/a | import linecache |
---|
43 | n/a | line = linecache.getline(msg.filename, msg.lineno) |
---|
44 | n/a | except Exception: |
---|
45 | n/a | # When a warning is logged during Python shutdown, linecache |
---|
46 | n/a | # and the import machinery don't work anymore |
---|
47 | n/a | line = None |
---|
48 | n/a | linecache = None |
---|
49 | n/a | else: |
---|
50 | n/a | line = msg.line |
---|
51 | n/a | if line: |
---|
52 | n/a | line = line.strip() |
---|
53 | n/a | s += " %s\n" % line |
---|
54 | n/a | |
---|
55 | n/a | if msg.source is not None: |
---|
56 | n/a | try: |
---|
57 | n/a | import tracemalloc |
---|
58 | n/a | tb = tracemalloc.get_object_traceback(msg.source) |
---|
59 | n/a | except Exception: |
---|
60 | n/a | # When a warning is logged during Python shutdown, tracemalloc |
---|
61 | n/a | # and the import machinery don't work anymore |
---|
62 | n/a | tb = None |
---|
63 | n/a | |
---|
64 | n/a | if tb is not None: |
---|
65 | n/a | s += 'Object allocated at (most recent call first):\n' |
---|
66 | n/a | for frame in tb: |
---|
67 | n/a | s += (' File "%s", lineno %s\n' |
---|
68 | n/a | % (frame.filename, frame.lineno)) |
---|
69 | n/a | |
---|
70 | n/a | try: |
---|
71 | n/a | if linecache is not None: |
---|
72 | n/a | line = linecache.getline(frame.filename, frame.lineno) |
---|
73 | n/a | else: |
---|
74 | n/a | line = None |
---|
75 | n/a | except Exception: |
---|
76 | n/a | line = None |
---|
77 | n/a | if line: |
---|
78 | n/a | line = line.strip() |
---|
79 | n/a | s += ' %s\n' % line |
---|
80 | n/a | return s |
---|
81 | n/a | |
---|
82 | n/a | # Keep a reference to check if the function was replaced |
---|
83 | n/a | _showwarning_orig = showwarning |
---|
84 | n/a | |
---|
85 | n/a | def _showwarnmsg(msg): |
---|
86 | n/a | """Hook to write a warning to a file; replace if you like.""" |
---|
87 | n/a | try: |
---|
88 | n/a | sw = showwarning |
---|
89 | n/a | except NameError: |
---|
90 | n/a | pass |
---|
91 | n/a | else: |
---|
92 | n/a | if sw is not _showwarning_orig: |
---|
93 | n/a | # warnings.showwarning() was replaced |
---|
94 | n/a | if not callable(sw): |
---|
95 | n/a | raise TypeError("warnings.showwarning() must be set to a " |
---|
96 | n/a | "function or method") |
---|
97 | n/a | |
---|
98 | n/a | sw(msg.message, msg.category, msg.filename, msg.lineno, |
---|
99 | n/a | msg.file, msg.line) |
---|
100 | n/a | return |
---|
101 | n/a | _showwarnmsg_impl(msg) |
---|
102 | n/a | |
---|
103 | n/a | # Keep a reference to check if the function was replaced |
---|
104 | n/a | _formatwarning_orig = formatwarning |
---|
105 | n/a | |
---|
106 | n/a | def _formatwarnmsg(msg): |
---|
107 | n/a | """Function to format a warning the standard way.""" |
---|
108 | n/a | try: |
---|
109 | n/a | fw = formatwarning |
---|
110 | n/a | except NameError: |
---|
111 | n/a | pass |
---|
112 | n/a | else: |
---|
113 | n/a | if fw is not _formatwarning_orig: |
---|
114 | n/a | # warnings.formatwarning() was replaced |
---|
115 | n/a | return fw(msg.message, msg.category, |
---|
116 | n/a | msg.filename, msg.lineno, line=msg.line) |
---|
117 | n/a | return _formatwarnmsg_impl(msg) |
---|
118 | n/a | |
---|
119 | n/a | def filterwarnings(action, message="", category=Warning, module="", lineno=0, |
---|
120 | n/a | append=False): |
---|
121 | n/a | """Insert an entry into the list of warnings filters (at the front). |
---|
122 | n/a | |
---|
123 | n/a | 'action' -- one of "error", "ignore", "always", "default", "module", |
---|
124 | n/a | or "once" |
---|
125 | n/a | 'message' -- a regex that the warning message must match |
---|
126 | n/a | 'category' -- a class that the warning must be a subclass of |
---|
127 | n/a | 'module' -- a regex that the module name must match |
---|
128 | n/a | 'lineno' -- an integer line number, 0 matches all warnings |
---|
129 | n/a | 'append' -- if true, append to the list of filters |
---|
130 | n/a | """ |
---|
131 | n/a | import re |
---|
132 | n/a | assert action in ("error", "ignore", "always", "default", "module", |
---|
133 | n/a | "once"), "invalid action: %r" % (action,) |
---|
134 | n/a | assert isinstance(message, str), "message must be a string" |
---|
135 | n/a | assert isinstance(category, type), "category must be a class" |
---|
136 | n/a | assert issubclass(category, Warning), "category must be a Warning subclass" |
---|
137 | n/a | assert isinstance(module, str), "module must be a string" |
---|
138 | n/a | assert isinstance(lineno, int) and lineno >= 0, \ |
---|
139 | n/a | "lineno must be an int >= 0" |
---|
140 | n/a | _add_filter(action, re.compile(message, re.I), category, |
---|
141 | n/a | re.compile(module), lineno, append=append) |
---|
142 | n/a | |
---|
143 | n/a | def simplefilter(action, category=Warning, lineno=0, append=False): |
---|
144 | n/a | """Insert a simple entry into the list of warnings filters (at the front). |
---|
145 | n/a | |
---|
146 | n/a | A simple filter matches all modules and messages. |
---|
147 | n/a | 'action' -- one of "error", "ignore", "always", "default", "module", |
---|
148 | n/a | or "once" |
---|
149 | n/a | 'category' -- a class that the warning must be a subclass of |
---|
150 | n/a | 'lineno' -- an integer line number, 0 matches all warnings |
---|
151 | n/a | 'append' -- if true, append to the list of filters |
---|
152 | n/a | """ |
---|
153 | n/a | assert action in ("error", "ignore", "always", "default", "module", |
---|
154 | n/a | "once"), "invalid action: %r" % (action,) |
---|
155 | n/a | assert isinstance(lineno, int) and lineno >= 0, \ |
---|
156 | n/a | "lineno must be an int >= 0" |
---|
157 | n/a | _add_filter(action, None, category, None, lineno, append=append) |
---|
158 | n/a | |
---|
159 | n/a | def _add_filter(*item, append): |
---|
160 | n/a | # Remove possible duplicate filters, so new one will be placed |
---|
161 | n/a | # in correct place. If append=True and duplicate exists, do nothing. |
---|
162 | n/a | if not append: |
---|
163 | n/a | try: |
---|
164 | n/a | filters.remove(item) |
---|
165 | n/a | except ValueError: |
---|
166 | n/a | pass |
---|
167 | n/a | filters.insert(0, item) |
---|
168 | n/a | else: |
---|
169 | n/a | if item not in filters: |
---|
170 | n/a | filters.append(item) |
---|
171 | n/a | _filters_mutated() |
---|
172 | n/a | |
---|
173 | n/a | def resetwarnings(): |
---|
174 | n/a | """Clear the list of warning filters, so that no filters are active.""" |
---|
175 | n/a | filters[:] = [] |
---|
176 | n/a | _filters_mutated() |
---|
177 | n/a | |
---|
178 | n/a | class _OptionError(Exception): |
---|
179 | n/a | """Exception used by option processing helpers.""" |
---|
180 | n/a | pass |
---|
181 | n/a | |
---|
182 | n/a | # Helper to process -W options passed via sys.warnoptions |
---|
183 | n/a | def _processoptions(args): |
---|
184 | n/a | for arg in args: |
---|
185 | n/a | try: |
---|
186 | n/a | _setoption(arg) |
---|
187 | n/a | except _OptionError as msg: |
---|
188 | n/a | print("Invalid -W option ignored:", msg, file=sys.stderr) |
---|
189 | n/a | |
---|
190 | n/a | # Helper for _processoptions() |
---|
191 | n/a | def _setoption(arg): |
---|
192 | n/a | import re |
---|
193 | n/a | parts = arg.split(':') |
---|
194 | n/a | if len(parts) > 5: |
---|
195 | n/a | raise _OptionError("too many fields (max 5): %r" % (arg,)) |
---|
196 | n/a | while len(parts) < 5: |
---|
197 | n/a | parts.append('') |
---|
198 | n/a | action, message, category, module, lineno = [s.strip() |
---|
199 | n/a | for s in parts] |
---|
200 | n/a | action = _getaction(action) |
---|
201 | n/a | message = re.escape(message) |
---|
202 | n/a | category = _getcategory(category) |
---|
203 | n/a | module = re.escape(module) |
---|
204 | n/a | if module: |
---|
205 | n/a | module = module + '$' |
---|
206 | n/a | if lineno: |
---|
207 | n/a | try: |
---|
208 | n/a | lineno = int(lineno) |
---|
209 | n/a | if lineno < 0: |
---|
210 | n/a | raise ValueError |
---|
211 | n/a | except (ValueError, OverflowError): |
---|
212 | n/a | raise _OptionError("invalid lineno %r" % (lineno,)) |
---|
213 | n/a | else: |
---|
214 | n/a | lineno = 0 |
---|
215 | n/a | filterwarnings(action, message, category, module, lineno) |
---|
216 | n/a | |
---|
217 | n/a | # Helper for _setoption() |
---|
218 | n/a | def _getaction(action): |
---|
219 | n/a | if not action: |
---|
220 | n/a | return "default" |
---|
221 | n/a | if action == "all": return "always" # Alias |
---|
222 | n/a | for a in ('default', 'always', 'ignore', 'module', 'once', 'error'): |
---|
223 | n/a | if a.startswith(action): |
---|
224 | n/a | return a |
---|
225 | n/a | raise _OptionError("invalid action: %r" % (action,)) |
---|
226 | n/a | |
---|
227 | n/a | # Helper for _setoption() |
---|
228 | n/a | def _getcategory(category): |
---|
229 | n/a | import re |
---|
230 | n/a | if not category: |
---|
231 | n/a | return Warning |
---|
232 | n/a | if re.match("^[a-zA-Z0-9_]+$", category): |
---|
233 | n/a | try: |
---|
234 | n/a | cat = eval(category) |
---|
235 | n/a | except NameError: |
---|
236 | n/a | raise _OptionError("unknown warning category: %r" % (category,)) |
---|
237 | n/a | else: |
---|
238 | n/a | i = category.rfind(".") |
---|
239 | n/a | module = category[:i] |
---|
240 | n/a | klass = category[i+1:] |
---|
241 | n/a | try: |
---|
242 | n/a | m = __import__(module, None, None, [klass]) |
---|
243 | n/a | except ImportError: |
---|
244 | n/a | raise _OptionError("invalid module name: %r" % (module,)) |
---|
245 | n/a | try: |
---|
246 | n/a | cat = getattr(m, klass) |
---|
247 | n/a | except AttributeError: |
---|
248 | n/a | raise _OptionError("unknown warning category: %r" % (category,)) |
---|
249 | n/a | if not issubclass(cat, Warning): |
---|
250 | n/a | raise _OptionError("invalid warning category: %r" % (category,)) |
---|
251 | n/a | return cat |
---|
252 | n/a | |
---|
253 | n/a | |
---|
254 | n/a | def _is_internal_frame(frame): |
---|
255 | n/a | """Signal whether the frame is an internal CPython implementation detail.""" |
---|
256 | n/a | filename = frame.f_code.co_filename |
---|
257 | n/a | return 'importlib' in filename and '_bootstrap' in filename |
---|
258 | n/a | |
---|
259 | n/a | |
---|
260 | n/a | def _next_external_frame(frame): |
---|
261 | n/a | """Find the next frame that doesn't involve CPython internals.""" |
---|
262 | n/a | frame = frame.f_back |
---|
263 | n/a | while frame is not None and _is_internal_frame(frame): |
---|
264 | n/a | frame = frame.f_back |
---|
265 | n/a | return frame |
---|
266 | n/a | |
---|
267 | n/a | |
---|
268 | n/a | # Code typically replaced by _warnings |
---|
269 | n/a | def warn(message, category=None, stacklevel=1, source=None): |
---|
270 | n/a | """Issue a warning, or maybe ignore it or raise an exception.""" |
---|
271 | n/a | # Check if message is already a Warning object |
---|
272 | n/a | if isinstance(message, Warning): |
---|
273 | n/a | category = message.__class__ |
---|
274 | n/a | # Check category argument |
---|
275 | n/a | if category is None: |
---|
276 | n/a | category = UserWarning |
---|
277 | n/a | if not (isinstance(category, type) and issubclass(category, Warning)): |
---|
278 | n/a | raise TypeError("category must be a Warning subclass, " |
---|
279 | n/a | "not '{:s}'".format(type(category).__name__)) |
---|
280 | n/a | # Get context information |
---|
281 | n/a | try: |
---|
282 | n/a | if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): |
---|
283 | n/a | # If frame is too small to care or if the warning originated in |
---|
284 | n/a | # internal code, then do not try to hide any frames. |
---|
285 | n/a | frame = sys._getframe(stacklevel) |
---|
286 | n/a | else: |
---|
287 | n/a | frame = sys._getframe(1) |
---|
288 | n/a | # Look for one frame less since the above line starts us off. |
---|
289 | n/a | for x in range(stacklevel-1): |
---|
290 | n/a | frame = _next_external_frame(frame) |
---|
291 | n/a | if frame is None: |
---|
292 | n/a | raise ValueError |
---|
293 | n/a | except ValueError: |
---|
294 | n/a | globals = sys.__dict__ |
---|
295 | n/a | lineno = 1 |
---|
296 | n/a | else: |
---|
297 | n/a | globals = frame.f_globals |
---|
298 | n/a | lineno = frame.f_lineno |
---|
299 | n/a | if '__name__' in globals: |
---|
300 | n/a | module = globals['__name__'] |
---|
301 | n/a | else: |
---|
302 | n/a | module = "<string>" |
---|
303 | n/a | filename = globals.get('__file__') |
---|
304 | n/a | if filename: |
---|
305 | n/a | fnl = filename.lower() |
---|
306 | n/a | if fnl.endswith(".pyc"): |
---|
307 | n/a | filename = filename[:-1] |
---|
308 | n/a | else: |
---|
309 | n/a | if module == "__main__": |
---|
310 | n/a | try: |
---|
311 | n/a | filename = sys.argv[0] |
---|
312 | n/a | except AttributeError: |
---|
313 | n/a | # embedded interpreters don't have sys.argv, see bug #839151 |
---|
314 | n/a | filename = '__main__' |
---|
315 | n/a | if not filename: |
---|
316 | n/a | filename = module |
---|
317 | n/a | registry = globals.setdefault("__warningregistry__", {}) |
---|
318 | n/a | warn_explicit(message, category, filename, lineno, module, registry, |
---|
319 | n/a | globals, source) |
---|
320 | n/a | |
---|
321 | n/a | def warn_explicit(message, category, filename, lineno, |
---|
322 | n/a | module=None, registry=None, module_globals=None, |
---|
323 | n/a | source=None): |
---|
324 | n/a | lineno = int(lineno) |
---|
325 | n/a | if module is None: |
---|
326 | n/a | module = filename or "<unknown>" |
---|
327 | n/a | if module[-3:].lower() == ".py": |
---|
328 | n/a | module = module[:-3] # XXX What about leading pathname? |
---|
329 | n/a | if registry is None: |
---|
330 | n/a | registry = {} |
---|
331 | n/a | if registry.get('version', 0) != _filters_version: |
---|
332 | n/a | registry.clear() |
---|
333 | n/a | registry['version'] = _filters_version |
---|
334 | n/a | if isinstance(message, Warning): |
---|
335 | n/a | text = str(message) |
---|
336 | n/a | category = message.__class__ |
---|
337 | n/a | else: |
---|
338 | n/a | text = message |
---|
339 | n/a | message = category(message) |
---|
340 | n/a | key = (text, category, lineno) |
---|
341 | n/a | # Quick test for common case |
---|
342 | n/a | if registry.get(key): |
---|
343 | n/a | return |
---|
344 | n/a | # Search the filters |
---|
345 | n/a | for item in filters: |
---|
346 | n/a | action, msg, cat, mod, ln = item |
---|
347 | n/a | if ((msg is None or msg.match(text)) and |
---|
348 | n/a | issubclass(category, cat) and |
---|
349 | n/a | (mod is None or mod.match(module)) and |
---|
350 | n/a | (ln == 0 or lineno == ln)): |
---|
351 | n/a | break |
---|
352 | n/a | else: |
---|
353 | n/a | action = defaultaction |
---|
354 | n/a | # Early exit actions |
---|
355 | n/a | if action == "ignore": |
---|
356 | n/a | registry[key] = 1 |
---|
357 | n/a | return |
---|
358 | n/a | |
---|
359 | n/a | # Prime the linecache for formatting, in case the |
---|
360 | n/a | # "file" is actually in a zipfile or something. |
---|
361 | n/a | import linecache |
---|
362 | n/a | linecache.getlines(filename, module_globals) |
---|
363 | n/a | |
---|
364 | n/a | if action == "error": |
---|
365 | n/a | raise message |
---|
366 | n/a | # Other actions |
---|
367 | n/a | if action == "once": |
---|
368 | n/a | registry[key] = 1 |
---|
369 | n/a | oncekey = (text, category) |
---|
370 | n/a | if onceregistry.get(oncekey): |
---|
371 | n/a | return |
---|
372 | n/a | onceregistry[oncekey] = 1 |
---|
373 | n/a | elif action == "always": |
---|
374 | n/a | pass |
---|
375 | n/a | elif action == "module": |
---|
376 | n/a | registry[key] = 1 |
---|
377 | n/a | altkey = (text, category, 0) |
---|
378 | n/a | if registry.get(altkey): |
---|
379 | n/a | return |
---|
380 | n/a | registry[altkey] = 1 |
---|
381 | n/a | elif action == "default": |
---|
382 | n/a | registry[key] = 1 |
---|
383 | n/a | else: |
---|
384 | n/a | # Unrecognized actions are errors |
---|
385 | n/a | raise RuntimeError( |
---|
386 | n/a | "Unrecognized action (%r) in warnings.filters:\n %s" % |
---|
387 | n/a | (action, item)) |
---|
388 | n/a | # Print message and context |
---|
389 | n/a | msg = WarningMessage(message, category, filename, lineno, source) |
---|
390 | n/a | _showwarnmsg(msg) |
---|
391 | n/a | |
---|
392 | n/a | |
---|
393 | n/a | class WarningMessage(object): |
---|
394 | n/a | |
---|
395 | n/a | _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file", |
---|
396 | n/a | "line", "source") |
---|
397 | n/a | |
---|
398 | n/a | def __init__(self, message, category, filename, lineno, file=None, |
---|
399 | n/a | line=None, source=None): |
---|
400 | n/a | local_values = locals() |
---|
401 | n/a | for attr in self._WARNING_DETAILS: |
---|
402 | n/a | setattr(self, attr, local_values[attr]) |
---|
403 | n/a | self._category_name = category.__name__ if category else None |
---|
404 | n/a | |
---|
405 | n/a | def __str__(self): |
---|
406 | n/a | return ("{message : %r, category : %r, filename : %r, lineno : %s, " |
---|
407 | n/a | "line : %r}" % (self.message, self._category_name, |
---|
408 | n/a | self.filename, self.lineno, self.line)) |
---|
409 | n/a | |
---|
410 | n/a | |
---|
411 | n/a | class catch_warnings(object): |
---|
412 | n/a | |
---|
413 | n/a | """A context manager that copies and restores the warnings filter upon |
---|
414 | n/a | exiting the context. |
---|
415 | n/a | |
---|
416 | n/a | The 'record' argument specifies whether warnings should be captured by a |
---|
417 | n/a | custom implementation of warnings.showwarning() and be appended to a list |
---|
418 | n/a | returned by the context manager. Otherwise None is returned by the context |
---|
419 | n/a | manager. The objects appended to the list are arguments whose attributes |
---|
420 | n/a | mirror the arguments to showwarning(). |
---|
421 | n/a | |
---|
422 | n/a | The 'module' argument is to specify an alternative module to the module |
---|
423 | n/a | named 'warnings' and imported under that name. This argument is only useful |
---|
424 | n/a | when testing the warnings module itself. |
---|
425 | n/a | |
---|
426 | n/a | """ |
---|
427 | n/a | |
---|
428 | n/a | def __init__(self, *, record=False, module=None): |
---|
429 | n/a | """Specify whether to record warnings and if an alternative module |
---|
430 | n/a | should be used other than sys.modules['warnings']. |
---|
431 | n/a | |
---|
432 | n/a | For compatibility with Python 3.0, please consider all arguments to be |
---|
433 | n/a | keyword-only. |
---|
434 | n/a | |
---|
435 | n/a | """ |
---|
436 | n/a | self._record = record |
---|
437 | n/a | self._module = sys.modules['warnings'] if module is None else module |
---|
438 | n/a | self._entered = False |
---|
439 | n/a | |
---|
440 | n/a | def __repr__(self): |
---|
441 | n/a | args = [] |
---|
442 | n/a | if self._record: |
---|
443 | n/a | args.append("record=True") |
---|
444 | n/a | if self._module is not sys.modules['warnings']: |
---|
445 | n/a | args.append("module=%r" % self._module) |
---|
446 | n/a | name = type(self).__name__ |
---|
447 | n/a | return "%s(%s)" % (name, ", ".join(args)) |
---|
448 | n/a | |
---|
449 | n/a | def __enter__(self): |
---|
450 | n/a | if self._entered: |
---|
451 | n/a | raise RuntimeError("Cannot enter %r twice" % self) |
---|
452 | n/a | self._entered = True |
---|
453 | n/a | self._filters = self._module.filters |
---|
454 | n/a | self._module.filters = self._filters[:] |
---|
455 | n/a | self._module._filters_mutated() |
---|
456 | n/a | self._showwarning = self._module.showwarning |
---|
457 | n/a | self._showwarnmsg_impl = self._module._showwarnmsg_impl |
---|
458 | n/a | if self._record: |
---|
459 | n/a | log = [] |
---|
460 | n/a | self._module._showwarnmsg_impl = log.append |
---|
461 | n/a | # Reset showwarning() to the default implementation to make sure |
---|
462 | n/a | # that _showwarnmsg() calls _showwarnmsg_impl() |
---|
463 | n/a | self._module.showwarning = self._module._showwarning_orig |
---|
464 | n/a | return log |
---|
465 | n/a | else: |
---|
466 | n/a | return None |
---|
467 | n/a | |
---|
468 | n/a | def __exit__(self, *exc_info): |
---|
469 | n/a | if not self._entered: |
---|
470 | n/a | raise RuntimeError("Cannot exit %r without entering first" % self) |
---|
471 | n/a | self._module.filters = self._filters |
---|
472 | n/a | self._module._filters_mutated() |
---|
473 | n/a | self._module.showwarning = self._showwarning |
---|
474 | n/a | self._module._showwarnmsg_impl = self._showwarnmsg_impl |
---|
475 | n/a | |
---|
476 | n/a | |
---|
477 | n/a | # filters contains a sequence of filter 5-tuples |
---|
478 | n/a | # The components of the 5-tuple are: |
---|
479 | n/a | # - an action: error, ignore, always, default, module, or once |
---|
480 | n/a | # - a compiled regex that must match the warning message |
---|
481 | n/a | # - a class representing the warning category |
---|
482 | n/a | # - a compiled regex that must match the module that is being warned |
---|
483 | n/a | # - a line number for the line being warning, or 0 to mean any line |
---|
484 | n/a | # If either if the compiled regexs are None, match anything. |
---|
485 | n/a | _warnings_defaults = False |
---|
486 | n/a | try: |
---|
487 | n/a | from _warnings import (filters, _defaultaction, _onceregistry, |
---|
488 | n/a | warn, warn_explicit, _filters_mutated) |
---|
489 | n/a | defaultaction = _defaultaction |
---|
490 | n/a | onceregistry = _onceregistry |
---|
491 | n/a | _warnings_defaults = True |
---|
492 | n/a | except ImportError: |
---|
493 | n/a | filters = [] |
---|
494 | n/a | defaultaction = "default" |
---|
495 | n/a | onceregistry = {} |
---|
496 | n/a | |
---|
497 | n/a | _filters_version = 1 |
---|
498 | n/a | |
---|
499 | n/a | def _filters_mutated(): |
---|
500 | n/a | global _filters_version |
---|
501 | n/a | _filters_version += 1 |
---|
502 | n/a | |
---|
503 | n/a | |
---|
504 | n/a | # Module initialization |
---|
505 | n/a | _processoptions(sys.warnoptions) |
---|
506 | n/a | if not _warnings_defaults: |
---|
507 | n/a | silence = [ImportWarning, PendingDeprecationWarning] |
---|
508 | n/a | silence.append(DeprecationWarning) |
---|
509 | n/a | for cls in silence: |
---|
510 | n/a | simplefilter("ignore", category=cls) |
---|
511 | n/a | bytes_warning = sys.flags.bytes_warning |
---|
512 | n/a | if bytes_warning > 1: |
---|
513 | n/a | bytes_action = "error" |
---|
514 | n/a | elif bytes_warning: |
---|
515 | n/a | bytes_action = "default" |
---|
516 | n/a | else: |
---|
517 | n/a | bytes_action = "ignore" |
---|
518 | n/a | simplefilter(bytes_action, category=BytesWarning, append=1) |
---|
519 | n/a | # resource usage warnings are enabled by default in pydebug mode |
---|
520 | n/a | if hasattr(sys, 'gettotalrefcount'): |
---|
521 | n/a | resource_action = "always" |
---|
522 | n/a | else: |
---|
523 | n/a | resource_action = "ignore" |
---|
524 | n/a | simplefilter(resource_action, category=ResourceWarning, append=1) |
---|
525 | n/a | |
---|
526 | n/a | del _warnings_defaults |
---|