Visitar URL original
deduperreload gives invalid tracebacks in reloaded functions · Issue #15359 · ipython/ipython · GitHub
Skip to content

deduperreload gives invalid tracebacks in reloaded functions #15359

Description

@yut23

When a function is reloaded with deduperreload, the line number information from the source file is lost. This breaks tracebacks, causing them to point to the start of the file instead of the correct source line. The reported line number matches the offset from the start of the function (plus one if the function is inside a class), but any comments and blank lines are ignored.

Tested with Python 3.13.14, IPython 9.15.0.

Python 3.13.14 | packaged by conda-forge | (main, Jun 12 2026, 09:50:25) [GCC 14.3.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 9.15.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: %load_ext autoreload

In [2]: %autoreload -p 1

In [3]: %%writefile module.py
   ...: """
   ...: The traceback incorrectly points to this line (line 2 of the file)
   ...: """
   ...: def func():
   ...:     assert False, "before reload"
   ...:
   ...:

In [4]: %aimport module

In [5]: module.func()
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[5], line 1
----> 1 module.func()

File /tmp/module.py:5, in func()
      4 def func():
----> 5     assert False, "before reload"

AssertionError: before reload

In [6]: %%writefile module.py
   ...: """
   ...: The traceback incorrectly points to this line (line 2 of the file)
   ...: """
   ...: def func():
   ...:     assert False, "after reload"
   ...:
   ...:
Overwriting module.py

In [7]: module.func()
Reloading 'module'.
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[7], line 1
----> 1 module.func()

File /tmp/module.py:2, in func()
      1 """
----> 2 The traceback incorrectly points to this line (line 2 of the file)
      3 """
      4 def func():
      5     assert False, "after reload"

AssertionError: after reload

Activity

  1. yut23 commented on Aug 7, 2026

    @yut23
    Author

    I'm not sure why DeduperReloader._patch_namespace_inner() unparses the AST node to text here instead of directly wrapping it with an ast.ClassDef:

    # exec new source code using old function's (obj) globals environment.
    func_code = textwrap.dedent(ast.unparse(new_ast_def))
    if is_method := (len(prefixes) > 0):
    func_code = "class __autoreload_class__:\n" + textwrap.indent(
    func_code, " "
    )

    Something like this should preserve all the line number information from the source file:

    @@ -446,11 +446,8 @@ def _patch_namespace_inner(
                     if isinstance(to_patch_to, (staticmethod, classmethod)):
                         to_patch_to = to_patch_to.__func__
                     # exec new source code using old function's (obj) globals environment.
    -                func_code = textwrap.dedent(ast.unparse(new_ast_def))
                     if is_method := (len(prefixes) > 0):
    -                    func_code = "class __autoreload_class__:\n" + textwrap.indent(
    -                        func_code, "    "
    -                    )
    +                    new_ast_def = ast.ClassDef(name="__autoreload_class__", body=[new_ast_def])
                     global_env = ns.__dict__
                     if not isinstance(global_env, dict):
                         global_env = dict(global_env)
    @@ -460,7 +457,7 @@ def _patch_namespace_inner(
                         and to_patch_to.__code__.co_filename
                         or "<string>"
                     )
    -                func_asts = [ast.parse(func_code)]
    +                func_asts = [new_ast_def]
                     if len(cast(ast.FunctionDef, func_asts[0].body[0]).decorator_list) > 0:
                         without_decorator_list = pickle.loads(pickle.dumps(func_asts[0]))
                         cast(
  2. yut23 commented on Aug 16, 2026

    @yut23
    Author

    I've been testing out #15369 locally, and found a deeper issue: the traceback of a non-reloaded function can point to the wrong line if the function definition was moved around in the file due to added or removed lines before it.

    It looks like it might be possible to update the function line numbers in-place with func.__code__ = func.__code__.replace(co_firstlineno=<new line number>).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions