Skip to content

Importing submodule overwrites global namespace in __init__.py #127623

@ChenyangGao

Description

@ChenyangGao

Bug report

Bug description:

Assume that I have a module with the following directory structure:

./test_module
├── __init__.py
└── myfunction.py

The specific code inside the files is as follows:

__init__.py

def myfunction():
    print("myfunction")

def main():
    myfunction()

myfunction.py is an empty file.

Python 3.13.0 | packaged by Anaconda, Inc. | (main, Oct  7 2024, 16:25:56) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_module import main
>>> main()
myfunction
>>> main.__globals__["myfunction"]
<function test_module.myfunction()>

Everything works fine up to this point, but when I import the myfunction module, it modifies the global namespace of the already imported __init__ module:

>>> from test_module.myfunction import *
>>> myfunction
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    myfunction
NameError: name 'myfunction' is not defined
>>> main()
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    main()
    ~~~~^^
  File "/Users/gcy/test_module/__init__.py", line 5, in main
    myfunction()
    ~~~~~~~~~~^^
TypeError: 'module' object is not callable
>>> main.__globals__["myfunction"]
<module 'test_module.myfunction' from '/Users/gcy/test_module/myfunction.py'>

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions