Debian Codegraph @

_pytest/_code/_py2traceback.py

raw symbols SCIP
1 # copied from python-2.7.3's traceback.py
2 # CHANGES:
3 # - some_str is replaced, trying to create unicode strings
4 #
5 import types
6
7 def format_exception_only(etype, value):
8 """Format the exception part of a traceback.
9
10 The arguments are the exception type and value such as given by
11 sys.last_type and sys.last_value. The return value is a list of
12 strings, each ending in a newline.
13
14 Normally, the list contains a single string; however, for
15 SyntaxError exceptions, it contains several lines that (when
16 printed) display detailed information about where the syntax
17 error occurred.
18
19 The message indicating which exception occurred is always the last
20 string in the list.
21
22 """
23
24 # An instance should not have a meaningful value parameter, but
25 # sometimes does, particularly for string exceptions, such as
26 # >>> raise string1, string2 # deprecated
27 #
28 # Clear these out first because issubtype(string1, SyntaxError)
29 # would throw another exception and mask the original problem.
30 if (isinstance(etype, BaseException) or
31 isinstance(etype, types.InstanceType) or
32 etype is None or type(etype) is str):
33 return [_format_final_exc_line(etype, value)]
34
35 stype = etype.__name__
36
37 if not issubclass(etype, SyntaxError):
38 return [_format_final_exc_line(stype, value)]
39
40 # It was a syntax error; show exactly where the problem was found.
41 lines = []
42 try:
43 msg, (filename, lineno, offset, badline) = value.args
44 except Exception:
45 pass
46 else:
47 filename = filename or "<string>"
48 lines.append(' File "%s", line %d\n' % (filename, lineno))
49 if badline is not None:
50 if isinstance(badline, bytes): # python 2 only
51 badline = badline.decode('utf-8', 'replace')
52 lines.append(u' %s\n' % badline.strip())
53 if offset is not None:
54 caretspace = badline.rstrip('\n')[:offset].lstrip()
55 # non-space whitespace (likes tabs) must be kept for alignment
56 caretspace = ((c.isspace() and c or ' ') for c in caretspace)
57 # only three spaces to account for offset1 == pos 0
58 lines.append(' %s^\n' % ''.join(caretspace))
59 value = msg
60
61 lines.append(_format_final_exc_line(stype, value))
62 return lines
63
64 def _format_final_exc_line(etype, value):
65 """Return a list of a single line -- normal case for format_exception_only"""
66 valuestr = _some_str(value)
67 if value is None or not valuestr:
68 line = "%s\n" % etype
69 else:
70 line = "%s: %s\n" % (etype, valuestr)
71 return line
72
73 def _some_str(value):
74 try:
75 return unicode(value)
76 except Exception:
77 try:
78 return str(value)
79 except Exception:
80 pass
81 return '<unprintable %s object>' % type(value).__name__