From 3f62ea72d56cd3af1802776241963235d00291c3 2018-11-26 00:36:00 From: Dan Allan Date: 2018-11-26 00:36:00 Subject: [PATCH] ENH: Accept one-off exception mode setting for %tb. This makes it easy to access a more verbose representation that the currently-active exception reporting mode provides. ```python In [1]: %xmode minimal Exception reporting mode: Minimal In [2]: def f(): ...: 3/0 ...: In [3]: f() ZeroDivisionError: division by zero In [4]: %tb verbose --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in ----> 1 f() global f = in f() 1 def f(): ----> 2 3/0 3 ZeroDivisionError: division by zero In [5]: f() # The default reporting mode has not been changed.... ZeroDivisionError: division by zero ``` --- diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index aac20df..b651a42 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -466,10 +466,35 @@ python-profiler package from non-free.""") @line_magic def tb(self, s): - """Print the last traceback with the currently active exception mode. + """Print the last traceback. - See %xmode for changing exception reporting modes.""" - self.shell.showtraceback() + Optionally, specify an exception reporting mode, tuning the + verbosity of the traceback. By default the currently-active exception + mode is used. See %xmode for changing exception reporting modes. + + Valid modes: Plain, Context, Verbose, and Minimal. + """ + interactive_tb = self.shell.InteractiveTB + if s: + # Switch exception reporting mode for this one call. + # Ensure it is switched back. + def xmode_switch_err(name): + warn('Error changing %s exception modes.\n%s' % + (name,sys.exc_info()[1])) + + new_mode = s.strip().capitalize() + original_mode = interactive_tb.mode + try: + try: + interactive_tb.set_mode(mode=new_mode) + except Exception: + xmode_switch_err('user') + else: + self.shell.showtraceback() + finally: + interactive_tb.set_mode(mode=original_mode) + else: + self.shell.showtraceback() @skip_doctest @line_magic