Skip to content

shadowing error with traceback module leads to unexpected code execution #138170

@tideofwords

Description

@tideofwords

Bug report

Bug description:

Python's traceback module is not a built-in module. This means that the user can shadow it by putting their own traceback.py file in the module search path. When an exception is raised, the exception-handling mechanism will try to import the traceback module, resulting in the unexpected execution of user-defined code.


Here is a minimal example in Python 3.13.5 with the CPython interpreter. I create two files, each with one line of code, and put them in the same directory:

a.py # this will raise an exception

print(x)

traceback.py # this will be called unexpectedly

print("THIS CODE SHOULD NOT RUN")

When I run a.py, the code in traceback.py also runs.

% python a.py
Traceback (most recent call last):
THIS CODE SHOULD NOT RUN
Traceback (most recent call last):
  File "/Users/brian/Documents/prog/bug/a.py", line 1, in <module>
    print(x)
NameError: name 'x' is not defined

I'm aware that module import shadowing is a known feature of the language. Usually, this issue only arises when the developer has either invoked import or redefined a built-in object -- so that there is some indication of the cause of the issue in the code itself. This case is unique in that the troublesome import occurs in the CPython implementation itself, and there is no sign in the Python code that a shadowing error might occur.

Note that built-in modules receive special treatment to prevent precisely this.
https://docs.python.org/3/tutorial/modules.html#the-module-search-path
The Python interpreter searches for built-in modules before searching sys.path. If traceback were a built-in module, this would not happen.


You can also get this behavior by shadowing other modules which are imported from traceback, such as ast. So if you rename traceback.py to ast.py in the example above, the same thing happens.

It seems that this is because when modules are imported in order to print a traceback, they are imported in sys.path order without checking builtins first.


The strange behavior first appeared after PR 110721 was approved.
#110702

CPython versions tested on:

3.13

Operating systems tested on:

Linux, macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions