deshaw / pyflyby

A set of productivity tools for Python
https://deshaw.github.io/pyflyby/
Other
357 stars 51 forks source link

pyflyby-dbg: Support chained exceptions #381

Open umairanis03 opened 6 days ago

umairanis03 commented 6 days ago

This commit adds support of stepping through chained exceptions with pyflyby debugger.

$ cat chained_exc.py
-------------------------------------------------------------
def inner():
    raise ValueError("inner")

def outer():
    try:
        inner()
    except Exception as e:
        raise ValueError("outer") from e

if __name__ == "__main__":
    outer()

--------------------------------------------------------------------------
$ py /u/anis/scratch/chained_exc.py
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File ~/scratch/chained_exc.py:6, in outer()
      5 try:
----> 6     inner()
      7 except Exception as e:

File ~/scratch/chained_exc.py:2, in inner()
      1 def inner():
----> 2     raise ValueError("inner")

ValueError: inner

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
File ~/scratch/chained_exc.py:11
      8         raise ValueError("outer") from e
     10 if __name__ == "__main__":
---> 11     outer()

File ~/scratch/chained_exc.py:8, in outer()
      6     inner()
      7 except Exception as e:
----> 8     raise ValueError("outer") from e

ValueError: outer
> /u/anis/scratch/chained_exc.py(8)outer()
      6         inner()
      7     except Exception as e:
----> 8         raise ValueError("outer") from e
      9
     10 if __name__ == "__main__":

ipdb> exceptions
    0 ValueError('inner')
>   1 ValueError('outer')

The support uses native Ipython's debugger or python's pdb support for chained exceptions and is available with exceptions command under ipdb/pdb command prompt.

Implementation notes

Starting Py3.13, pdb.interaction() supports chained exceptions in case exception (and not traceback) is specified. This support is backported to IPython8.16 for earlier Python versions. So the conditions where chained exceptions won't be supported from pyflyby's debugger would be with Python version < 3.13 and ipython is not being installed, or IPython's version is lesser than 8.16.

Ref: PyInf#14001 Reviewer: dhamodha

umairanis03 commented 6 days ago

@dshivashankar1994 Could you please review the change here?