diff -r c0224ff67cdd -r 9cb7aaad1d85 Lib/traceback.py --- a/Lib/traceback.py Mon Oct 13 10:39:41 2014 +0100 +++ b/Lib/traceback.py Mon Oct 13 14:43:06 2014 +0000 @@ -3,6 +3,8 @@ import linecache import sys import operator +import types +import collections __all__ = ['extract_stack', 'extract_tb', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', @@ -51,7 +53,14 @@ # - Next item (same type as curr) # In practice, curr is either a traceback or a frame. def _extract_tb_or_stack_iter(curr, limit, extractor): - if limit is None: + # Check if limit is negative and curr is a traceback + cond = limit is not None and limit < 0 \ + and isinstance(curr, types.TracebackType) + # Collect last abs(limit) traceback entries. O(1) for pop operations + if cond: + seq = collections.deque(maxlen=abs(limit)) + + if limit is None or cond: limit = getattr(sys, 'tracebacklimit', None) n = 0 @@ -61,18 +70,25 @@ filename = co.co_filename name = co.co_name - linecache.checkcache(filename) - line = linecache.getline(filename, lineno, f.f_globals) + if not cond: + # Positive limit; load source immediately + linecache.checkcache(filename) + line = linecache.getline(filename, lineno, f.f_globals) + yield (filename, lineno, name, line.strip() if line else None) + else: + # Negative limit; load source after the loop. The last tuple + # element is a frame globals + seq.append((filename, lineno, name, f.f_globals)) - if line: - line = line.strip() - else: - line = None - - yield (filename, lineno, name, line) curr = next_item n += 1 + if cond: + for x in seq: + linecache.checkcache(x[0]) + line = linecache.getline(x[0], x[1], x[-1]) + yield x[:-1] + (line.strip() if line else None,) + def _extract_tb_iter(tb, limit): return _extract_tb_or_stack_iter( tb, limit,