From 8bef245745620c73ec2feafb73cc8af4e998a3b0 2024-02-19 13:36:42 From: Matthias Bussonnier Date: 2024-02-19 13:36:42 Subject: [PATCH] Fix for dynamically evaluated source code traceback And add test. This should close #14057 --- diff --git a/IPython/core/tests/test_ultratb.py b/IPython/core/tests/test_ultratb.py index c4de95d..e167d99 100644 --- a/IPython/core/tests/test_ultratb.py +++ b/IPython/core/tests/test_ultratb.py @@ -14,7 +14,7 @@ from tempfile import TemporaryDirectory from IPython.core.ultratb import ColorTB, VerboseTB from IPython.testing import tools as tt -from IPython.testing.decorators import onlyif_unicode_paths +from IPython.testing.decorators import onlyif_unicode_paths, skip_without from IPython.utils.syspathcontext import prepended_to_syspath file_1 = """1 @@ -177,6 +177,20 @@ class IndentationErrorTest(unittest.TestCase): with tt.AssertPrints("zoon()", suppress=False): ip.magic('run %s' % fname) +@skip_without("pandas") +def test_dynamic_code(): + code = """ + import pandas + df = pandas.DataFrame([]) + + # Important: only fails inside of an "exec" call: + exec("df.foobarbaz()") + """ + + with tt.AssertPrints("Could not get source"): + ip.run_cell(code) + + se_file_1 = """1 2 7/ diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index 0e4a097..cc139b1 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -743,6 +743,7 @@ class FrameInfo: lineno: Tuple[int] # number of context lines to use context: Optional[int] + raw_lines: List[str] @classmethod def _from_stack_data_FrameInfo(cls, frame_info): @@ -777,8 +778,13 @@ class FrameInfo: # self.lines = [] if sd is None: - ix = inspect.getsourcelines(frame) - self.raw_lines = ix[0] + try: + # return a list of source lines and a starting line number + self.raw_lines = inspect.getsourcelines(frame)[0] + except OSError: + self.raw_lines = [ + "'Could not get source, probably due dynamically evaluated source code.'" + ] @property def variables_in_executing_piece(self):