Debian Codegraph @

_pytest/_code/code.py

raw symbols SCIP
1 import sys
2 from inspect import CO_VARARGS, CO_VARKEYWORDS
3
4 import py
5
6 builtin_repr = repr
7
8 reprlib = py.builtin._tryimport('repr', 'reprlib')
9
10 if sys.version_info[0] >= 3:
11 from traceback import format_exception_only
12 else:
13 from ._py2traceback import format_exception_only
14
15 class Code(object):
16 """ wrapper around Python code objects """
17 def __init__(self, rawcode):
18 if not hasattr(rawcode, "co_filename"):
19 rawcode = getrawcode(rawcode)
20 try:
21 self.filename = rawcode.co_filename
22 self.firstlineno = rawcode.co_firstlineno - 1
23 self.name = rawcode.co_name
24 except AttributeError:
25 raise TypeError("not a code object: %r" %(rawcode,))
26 self.raw = rawcode
27
28 def __eq__(self, other):
29 return self.raw == other.raw
30
31 def __ne__(self, other):
32 return not self == other
33
34 @property
35 def path(self):
36 """ return a path object pointing to source code (note that it
37 might not point to an actually existing file). """
38 p = py.path.local(self.raw.co_filename)
39 # maybe don't try this checking
40 if not p.check():
41 # XXX maybe try harder like the weird logic
42 # in the standard lib [linecache.updatecache] does?
43 p = self.raw.co_filename
44 return p
45
46 @property
47 def fullsource(self):
48 """ return a _pytest._code.Source object for the full source file of the code
49 """
50 from _pytest._code import source
51 full, _ = source.findsource(self.raw)
52 return full
53
54 def source(self):
55 """ return a _pytest._code.Source object for the code object's source only
56 """
57 # return source only for that part of code
58 import _pytest._code
59 return _pytest._code.Source(self.raw)
60
61 def getargs(self, var=False):
62 """ return a tuple with the argument names for the code object
63
64 if 'var' is set True also return the names of the variable and
65 keyword arguments when present
66 """
67 # handfull shortcut for getting args
68 raw = self.raw
69 argcount = raw.co_argcount
70 if var:
71 argcount += raw.co_flags & CO_VARARGS
72 argcount += raw.co_flags & CO_VARKEYWORDS
73 return raw.co_varnames[:argcount]
74
75 class Frame(object):
76 """Wrapper around a Python frame holding f_locals and f_globals
77 in which expressions can be evaluated."""
78
79 def __init__(self, frame):
80 self.lineno = frame.f_lineno - 1
81 self.f_globals = frame.f_globals
82 self.f_locals = frame.f_locals
83 self.raw = frame
84 self.code = Code(frame.f_code)
85
86 @property
87 def statement(self):
88 """ statement this frame is at """
89 import _pytest._code
90 if self.code.fullsource is None:
91 return _pytest._code.Source("")
92 return self.code.fullsource.getstatement(self.lineno)
93
94 def eval(self, code, **vars):
95 """ evaluate 'code' in the frame
96
97 'vars' are optional additional local variables
98
99 returns the result of the evaluation
100 """
101 f_locals = self.f_locals.copy()
102 f_locals.update(vars)
103 return eval(code, self.f_globals, f_locals)
104
105 def exec_(self, code, **vars):
106 """ exec 'code' in the frame
107
108 'vars' are optiona; additional local variables
109 """
110 f_locals = self.f_locals.copy()
111 f_locals.update(vars)
112 py.builtin.exec_(code, self.f_globals, f_locals )
113
114 def repr(self, object):
115 """ return a 'safe' (non-recursive, one-line) string repr for 'object'
116 """
117 return py.io.saferepr(object)
118
119 def is_true(self, object):
120 return object
121
122 def getargs(self, var=False):
123 """ return a list of tuples (name, value) for all arguments
124
125 if 'var' is set True also include the variable and keyword
126 arguments when present
127 """
128 retval = []
129 for arg in self.code.getargs(var):
130 try:
131 retval.append((arg, self.f_locals[arg]))
132 except KeyError:
133 pass # this can occur when using Psyco
134 return retval
135
136 class TracebackEntry(object):
137 """ a single entry in a traceback """
138
139 _repr_style = None
140 exprinfo = None
141
142 def __init__(self, rawentry):
143 self._rawentry = rawentry
144 self.lineno = rawentry.tb_lineno - 1
145
146 def set_repr_style(self, mode):
147 assert mode in ("short", "long")
148 self._repr_style = mode
149
150 @property
151 def frame(self):
152 import _pytest._code
153 return _pytest._code.Frame(self._rawentry.tb_frame)
154
155 @property
156 def relline(self):
157 return self.lineno - self.frame.code.firstlineno
158
159 def __repr__(self):
160 return "<TracebackEntry %s:%d>" %(self.frame.code.path, self.lineno+1)
161
162 @property
163 def statement(self):
164 """ _pytest._code.Source object for the current statement """
165 source = self.frame.code.fullsource
166 return source.getstatement(self.lineno)
167
168 @property
169 def path(self):
170 """ path to the source code """
171 return self.frame.code.path
172
173 def getlocals(self):
174 return self.frame.f_locals
175 locals = property(getlocals, None, None, "locals of underlaying frame")
176
177 def reinterpret(self):
178 """Reinterpret the failing statement and returns a detailed information
179 about what operations are performed."""
180 from _pytest.assertion.reinterpret import reinterpret
181 if self.exprinfo is None:
182 source = py.builtin._totext(self.statement).strip()
183 x = reinterpret(source, self.frame, should_fail=True)
184 if not py.builtin._istext(x):
185 raise TypeError("interpret returned non-string %r" % (x,))
186 self.exprinfo = x
187 return self.exprinfo
188
189 def getfirstlinesource(self):
190 # on Jython this firstlineno can be -1 apparently
191 return max(self.frame.code.firstlineno, 0)
192
193 def getsource(self, astcache=None):
194 """ return failing source code. """
195 # we use the passed in astcache to not reparse asttrees
196 # within exception info printing
197 from _pytest._code.source import getstatementrange_ast
198 source = self.frame.code.fullsource
199 if source is None:
200 return None
201 key = astnode = None
202 if astcache is not None:
203 key = self.frame.code.path
204 if key is not None:
205 astnode = astcache.get(key, None)
206 start = self.getfirstlinesource()
207 try:
208 astnode, _, end = getstatementrange_ast(self.lineno, source,
209 astnode=astnode)
210 except SyntaxError:
211 end = self.lineno + 1
212 else:
213 if key is not None:
214 astcache[key] = astnode
215 return source[start:end]
216
217 source = property(getsource)
218
219 def ishidden(self):
220 """ return True if the current frame has a var __tracebackhide__
221 resolving to True
222
223 mostly for internal use
224 """
225 try:
226 return self.frame.f_locals['__tracebackhide__']
227 except KeyError:
228 try:
229 return self.frame.f_globals['__tracebackhide__']
230 except KeyError:
231 return False
232
233 def __str__(self):
234 try:
235 fn = str(self.path)
236 except py.error.Error:
237 fn = '???'
238 name = self.frame.code.name
239 try:
240 line = str(self.statement).lstrip()
241 except KeyboardInterrupt:
242 raise
243 except:
244 line = "???"
245 return " File %r:%d in %s\n %s\n" %(fn, self.lineno+1, name, line)
246
247 def name(self):
248 return self.frame.code.raw.co_name
249 name = property(name, None, None, "co_name of underlaying code")
250
251 class Traceback(list):
252 """ Traceback objects encapsulate and offer higher level
253 access to Traceback entries.
254 """
255 Entry = TracebackEntry
256 def __init__(self, tb):
257 """ initialize from given python traceback object. """
258 if hasattr(tb, 'tb_next'):
259 def f(cur):
260 while cur is not None:
261 yield self.Entry(cur)
262 cur = cur.tb_next
263 list.__init__(self, f(tb))
264 else:
265 list.__init__(self, tb)
266
267 def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
268 """ return a Traceback instance wrapping part of this Traceback
269
270 by provding any combination of path, lineno and firstlineno, the
271 first frame to start the to-be-returned traceback is determined
272
273 this allows cutting the first part of a Traceback instance e.g.
274 for formatting reasons (removing some uninteresting bits that deal
275 with handling of the exception/traceback)
276 """
277 for x in self:
278 code = x.frame.code
279 codepath = code.path
280 if ((path is None or codepath == path) and
281 (excludepath is None or not hasattr(codepath, 'relto') or
282 not codepath.relto(excludepath)) and
283 (lineno is None or x.lineno == lineno) and
284 (firstlineno is None or x.frame.code.firstlineno == firstlineno)):
285 return Traceback(x._rawentry)
286 return self
287
288 def __getitem__(self, key):
289 val = super(Traceback, self).__getitem__(key)
290 if isinstance(key, type(slice(0))):
291 val = self.__class__(val)
292 return val
293
294 def filter(self, fn=lambda x: not x.ishidden()):
295 """ return a Traceback instance with certain items removed
296
297 fn is a function that gets a single argument, a TracebackEntry
298 instance, and should return True when the item should be added
299 to the Traceback, False when not
300
301 by default this removes all the TracebackEntries which are hidden
302 (see ishidden() above)
303 """
304 return Traceback(filter(fn, self))
305
306 def getcrashentry(self):
307 """ return last non-hidden traceback entry that lead
308 to the exception of a traceback.
309 """
310 for i in range(-1, -len(self)-1, -1):
311 entry = self[i]
312 if not entry.ishidden():
313 return entry
314 return self[-1]
315
316 def recursionindex(self):
317 """ return the index of the frame/TracebackEntry where recursion
318 originates if appropriate, None if no recursion occurred
319 """
320 cache = {}
321 for i, entry in enumerate(self):
322 # id for the code.raw is needed to work around
323 # the strange metaprogramming in the decorator lib from pypi
324 # which generates code objects that have hash/value equality
325 #XXX needs a test
326 key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
327 #print "checking for recursion at", key
328 l = cache.setdefault(key, [])
329 if l:
330 f = entry.frame
331 loc = f.f_locals
332 for otherloc in l:
333 if f.is_true(f.eval(co_equal,
334 __recursioncache_locals_1=loc,
335 __recursioncache_locals_2=otherloc)):
336 return i
337 l.append(entry.frame.f_locals)
338 return None
339
340 co_equal = compile('__recursioncache_locals_1 == __recursioncache_locals_2',
341 '?', 'eval')
342
343 class ExceptionInfo(object):
344 """ wraps sys.exc_info() objects and offers
345 help for navigating the traceback.
346 """
347 _striptext = ''
348 def __init__(self, tup=None, exprinfo=None):
349 import _pytest._code
350 if tup is None:
351 tup = sys.exc_info()
352 if exprinfo is None and isinstance(tup[1], AssertionError):
353 exprinfo = getattr(tup[1], 'msg', None)
354 if exprinfo is None:
355 exprinfo = str(tup[1])
356 if exprinfo and exprinfo.startswith('assert '):
357 self._striptext = 'AssertionError: '
358 self._excinfo = tup
359 #: the exception class
360 self.type = tup[0]
361 #: the exception instance
362 self.value = tup[1]
363 #: the exception raw traceback
364 self.tb = tup[2]
365 #: the exception type name
366 self.typename = self.type.__name__
367 #: the exception traceback (_pytest._code.Traceback instance)
368 self.traceback = _pytest._code.Traceback(self.tb)
369
370 def __repr__(self):
371 return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
372
373 def exconly(self, tryshort=False):
374 """ return the exception as a string
375
376 when 'tryshort' resolves to True, and the exception is a
377 _pytest._code._AssertionError, only the actual exception part of
378 the exception representation is returned (so 'AssertionError: ' is
379 removed from the beginning)
380 """
381 lines = format_exception_only(self.type, self.value)
382 text = ''.join(lines)
383 text = text.rstrip()
384 if tryshort:
385 if text.startswith(self._striptext):
386 text = text[len(self._striptext):]
387 return text
388
389 def errisinstance(self, exc):
390 """ return True if the exception is an instance of exc """
391 return isinstance(self.value, exc)
392
393 def _getreprcrash(self):
394 exconly = self.exconly(tryshort=True)
395 entry = self.traceback.getcrashentry()
396 path, lineno = entry.frame.code.raw.co_filename, entry.lineno
397 return ReprFileLocation(path, lineno+1, exconly)
398
399 def getrepr(self, showlocals=False, style="long",
400 abspath=False, tbfilter=True, funcargs=False):
401 """ return str()able representation of this exception info.
402 showlocals: show locals per traceback entry
403 style: long|short|no|native traceback style
404 tbfilter: hide entries (where __tracebackhide__ is true)
405
406 in case of style==native, tbfilter and showlocals is ignored.
407 """
408 if style == 'native':
409 return ReprExceptionInfo(ReprTracebackNative(
410 py.std.traceback.format_exception(
411 self.type,
412 self.value,
413 self.traceback[0]._rawentry,
414 )), self._getreprcrash())
415
416 fmt = FormattedExcinfo(showlocals=showlocals, style=style,
417 abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
418 return fmt.repr_excinfo(self)
419
420 def __str__(self):
421 entry = self.traceback[-1]
422 loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
423 return str(loc)
424
425 def __unicode__(self):
426 entry = self.traceback[-1]
427 loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
428 return unicode(loc)
429
430
431 class FormattedExcinfo(object):
432 """ presenting information about failing Functions and Generators. """
433 # for traceback entries
434 flow_marker = ">"
435 fail_marker = "E"
436
437 def __init__(self, showlocals=False, style="long", abspath=True, tbfilter=True, funcargs=False):
438 self.showlocals = showlocals
439 self.style = style
440 self.tbfilter = tbfilter
441 self.funcargs = funcargs
442 self.abspath = abspath
443 self.astcache = {}
444
445 def _getindent(self, source):
446 # figure out indent for given source
447 try:
448 s = str(source.getstatement(len(source)-1))
449 except KeyboardInterrupt:
450 raise
451 except:
452 try:
453 s = str(source[-1])
454 except KeyboardInterrupt:
455 raise
456 except:
457 return 0
458 return 4 + (len(s) - len(s.lstrip()))
459
460 def _getentrysource(self, entry):
461 source = entry.getsource(self.astcache)
462 if source is not None:
463 source = source.deindent()
464 return source
465
466 def _saferepr(self, obj):
467 return py.io.saferepr(obj)
468
469 def repr_args(self, entry):
470 if self.funcargs:
471 args = []
472 for argname, argvalue in entry.frame.getargs(var=True):
473 args.append((argname, self._saferepr(argvalue)))
474 return ReprFuncArgs(args)
475
476 def get_source(self, source, line_index=-1, excinfo=None, short=False):
477 """ return formatted and marked up source lines. """
478 import _pytest._code
479 lines = []
480 if source is None or line_index >= len(source.lines):
481 source = _pytest._code.Source("???")
482 line_index = 0
483 if line_index < 0:
484 line_index += len(source)
485 space_prefix = " "
486 if short:
487 lines.append(space_prefix + source.lines[line_index].strip())
488 else:
489 for line in source.lines[:line_index]:
490 lines.append(space_prefix + line)
491 lines.append(self.flow_marker + " " + source.lines[line_index])
492 for line in source.lines[line_index+1:]:
493 lines.append(space_prefix + line)
494 if excinfo is not None:
495 indent = 4 if short else self._getindent(source)
496 lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
497 return lines
498
499 def get_exconly(self, excinfo, indent=4, markall=False):
500 lines = []
501 indent = " " * indent
502 # get the real exception information out
503 exlines = excinfo.exconly(tryshort=True).split('\n')
504 failindent = self.fail_marker + indent[1:]
505 for line in exlines:
506 lines.append(failindent + line)
507 if not markall:
508 failindent = indent
509 return lines
510
511 def repr_locals(self, locals):
512 if self.showlocals:
513 lines = []
514 keys = [loc for loc in locals if loc[0] != "@"]
515 keys.sort()
516 for name in keys:
517 value = locals[name]
518 if name == '__builtins__':
519 lines.append("__builtins__ = <builtins>")
520 else:
521 # This formatting could all be handled by the
522 # _repr() function, which is only reprlib.Repr in
523 # disguise, so is very configurable.
524 str_repr = self._saferepr(value)
525 #if len(str_repr) < 70 or not isinstance(value,
526 # (list, tuple, dict)):
527 lines.append("%-10s = %s" %(name, str_repr))
528 #else:
529 # self._line("%-10s =\\" % (name,))
530 # # XXX
531 # py.std.pprint.pprint(value, stream=self.excinfowriter)
532 return ReprLocals(lines)
533
534 def repr_traceback_entry(self, entry, excinfo=None):
535 import _pytest._code
536 source = self._getentrysource(entry)
537 if source is None:
538 source = _pytest._code.Source("???")
539 line_index = 0
540 else:
541 # entry.getfirstlinesource() can be -1, should be 0 on jython
542 line_index = entry.lineno - max(entry.getfirstlinesource(), 0)
543
544 lines = []
545 style = entry._repr_style
546 if style is None:
547 style = self.style
548 if style in ("short", "long"):
549 short = style == "short"
550 reprargs = self.repr_args(entry) if not short else None
551 s = self.get_source(source, line_index, excinfo, short=short)
552 lines.extend(s)
553 if short:
554 message = "in %s" %(entry.name)
555 else:
556 message = excinfo and excinfo.typename or ""
557 path = self._makepath(entry.path)
558 filelocrepr = ReprFileLocation(path, entry.lineno+1, message)
559 localsrepr = None
560 if not short:
561 localsrepr = self.repr_locals(entry.locals)
562 return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
563 if excinfo:
564 lines.extend(self.get_exconly(excinfo, indent=4))
565 return ReprEntry(lines, None, None, None, style)
566
567 def _makepath(self, path):
568 if not self.abspath:
569 try:
570 np = py.path.local().bestrelpath(path)
571 except OSError:
572 return path
573 if len(np) < len(str(path)):
574 path = np
575 return path
576
577 def repr_traceback(self, excinfo):
578 traceback = excinfo.traceback
579 if self.tbfilter:
580 traceback = traceback.filter()
581 recursionindex = None
582 if is_recursion_error(excinfo):
583 recursionindex = traceback.recursionindex()
584 last = traceback[-1]
585 entries = []
586 extraline = None
587 for index, entry in enumerate(traceback):
588 einfo = (last == entry) and excinfo or None
589 reprentry = self.repr_traceback_entry(entry, einfo)
590 entries.append(reprentry)
591 if index == recursionindex:
592 extraline = "!!! Recursion detected (same locals & position)"
593 break
594 return ReprTraceback(entries, extraline, style=self.style)
595
596 def repr_excinfo(self, excinfo):
597 reprtraceback = self.repr_traceback(excinfo)
598 reprcrash = excinfo._getreprcrash()
599 return ReprExceptionInfo(reprtraceback, reprcrash)
600
601 class TerminalRepr:
602 def __str__(self):
603 s = self.__unicode__()
604 if sys.version_info[0] < 3 and isinstance(s, unicode):
605 s = s.encode('utf-8')
606 return s
607
608 def __unicode__(self):
609 # FYI this is called from pytest-xdist's serialization of exception
610 # information.
611 io = py.io.TextIO()
612 tw = py.io.TerminalWriter(file=io)
613 self.toterminal(tw)
614 return io.getvalue().strip()
615
616 def __repr__(self):
617 return "<%s instance at %0x>" %(self.__class__, id(self))
618
619
620 class ReprExceptionInfo(TerminalRepr):
621 def __init__(self, reprtraceback, reprcrash):
622 self.reprtraceback = reprtraceback
623 self.reprcrash = reprcrash
624 self.sections = []
625
626 def addsection(self, name, content, sep="-"):
627 self.sections.append((name, content, sep))
628
629 def toterminal(self, tw):
630 self.reprtraceback.toterminal(tw)
631 for name, content, sep in self.sections:
632 tw.sep(sep, name)
633 tw.line(content)
634
635 class ReprTraceback(TerminalRepr):
636 entrysep = "_ "
637
638 def __init__(self, reprentries, extraline, style):
639 self.reprentries = reprentries
640 self.extraline = extraline
641 self.style = style
642
643 def toterminal(self, tw):
644 # the entries might have different styles
645 for i, entry in enumerate(self.reprentries):
646 if entry.style == "long":
647 tw.line("")
648 entry.toterminal(tw)
649 if i < len(self.reprentries) - 1:
650 next_entry = self.reprentries[i+1]
651 if entry.style == "long" or \
652 entry.style == "short" and next_entry.style == "long":
653 tw.sep(self.entrysep)
654
655 if self.extraline:
656 tw.line(self.extraline)
657
658 class ReprTracebackNative(ReprTraceback):
659 def __init__(self, tblines):
660 self.style = "native"
661 self.reprentries = [ReprEntryNative(tblines)]
662 self.extraline = None
663
664 class ReprEntryNative(TerminalRepr):
665 style = "native"
666
667 def __init__(self, tblines):
668 self.lines = tblines
669
670 def toterminal(self, tw):
671 tw.write("".join(self.lines))
672
673 class ReprEntry(TerminalRepr):
674 localssep = "_ "
675
676 def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):
677 self.lines = lines
678 self.reprfuncargs = reprfuncargs
679 self.reprlocals = reprlocals
680 self.reprfileloc = filelocrepr
681 self.style = style
682
683 def toterminal(self, tw):
684 if self.style == "short":
685 self.reprfileloc.toterminal(tw)
686 for line in self.lines:
687 red = line.startswith("E ")
688 tw.line(line, bold=True, red=red)
689 #tw.line("")
690 return
691 if self.reprfuncargs:
692 self.reprfuncargs.toterminal(tw)
693 for line in self.lines:
694 red = line.startswith("E ")
695 tw.line(line, bold=True, red=red)
696 if self.reprlocals:
697 #tw.sep(self.localssep, "Locals")
698 tw.line("")
699 self.reprlocals.toterminal(tw)
700 if self.reprfileloc:
701 if self.lines:
702 tw.line("")
703 self.reprfileloc.toterminal(tw)
704
705 def __str__(self):
706 return "%s\n%s\n%s" % ("\n".join(self.lines),
707 self.reprlocals,
708 self.reprfileloc)
709
710 class ReprFileLocation(TerminalRepr):
711 def __init__(self, path, lineno, message):
712 self.path = str(path)
713 self.lineno = lineno
714 self.message = message
715
716 def toterminal(self, tw):
717 # filename and lineno output for each entry,
718 # using an output format that most editors unterstand
719 msg = self.message
720 i = msg.find("\n")
721 if i != -1:
722 msg = msg[:i]
723 tw.line("%s:%s: %s" %(self.path, self.lineno, msg))
724
725 class ReprLocals(TerminalRepr):
726 def __init__(self, lines):
727 self.lines = lines
728
729 def toterminal(self, tw):
730 for line in self.lines:
731 tw.line(line)
732
733 class ReprFuncArgs(TerminalRepr):
734 def __init__(self, args):
735 self.args = args
736
737 def toterminal(self, tw):
738 if self.args:
739 linesofar = ""
740 for name, value in self.args:
741 ns = "%s = %s" %(name, value)
742 if len(ns) + len(linesofar) + 2 > tw.fullwidth:
743 if linesofar:
744 tw.line(linesofar)
745 linesofar = ns
746 else:
747 if linesofar:
748 linesofar += ", " + ns
749 else:
750 linesofar = ns
751 if linesofar:
752 tw.line(linesofar)
753 tw.line("")
754
755
756
757 oldbuiltins = {}
758
759 def patch_builtins(assertion=True, compile=True):
760 """ put compile and AssertionError builtins to Python's builtins. """
761 if assertion:
762 from _pytest.assertion import reinterpret
763 l = oldbuiltins.setdefault('AssertionError', [])
764 l.append(py.builtin.builtins.AssertionError)
765 py.builtin.builtins.AssertionError = reinterpret.AssertionError
766 if compile:
767 import _pytest._code
768 l = oldbuiltins.setdefault('compile', [])
769 l.append(py.builtin.builtins.compile)
770 py.builtin.builtins.compile = _pytest._code.compile
771
772 def unpatch_builtins(assertion=True, compile=True):
773 """ remove compile and AssertionError builtins from Python builtins. """
774 if assertion:
775 py.builtin.builtins.AssertionError = oldbuiltins['AssertionError'].pop()
776 if compile:
777 py.builtin.builtins.compile = oldbuiltins['compile'].pop()
778
779 def getrawcode(obj, trycall=True):
780 """ return code object for given function. """
781 try:
782 return obj.__code__
783 except AttributeError:
784 obj = getattr(obj, 'im_func', obj)
785 obj = getattr(obj, 'func_code', obj)
786 obj = getattr(obj, 'f_code', obj)
787 obj = getattr(obj, '__code__', obj)
788 if trycall and not hasattr(obj, 'co_firstlineno'):
789 if hasattr(obj, '__call__') and not py.std.inspect.isclass(obj):
790 x = getrawcode(obj.__call__, trycall=False)
791 if hasattr(x, 'co_firstlineno'):
792 return x
793 return obj
794
795 if sys.version_info[:2] >= (3, 5): # RecursionError introduced in 3.5
796 def is_recursion_error(excinfo):
797 return excinfo.errisinstance(RecursionError) # noqa
798 else:
799 def is_recursion_error(excinfo):
800 if not excinfo.errisinstance(RuntimeError):
801 return False
802 try:
803 return "maximum recursion depth exceeded" in str(excinfo.value)
804 except UnicodeError:
805 return False