Accidentally shadowing modules by giving your python file the same name is one of the most notorious gotchas in python, which every now and then still manages to make otherwise experienced developers stumble, e.g.
- I'm stumped by this (a post I found while looking if this post has already been made)
- Issue 29929: Eliminate implicit __main__ relative imports - Python tracker (ncoghlan, with examples and a partial workaround)
- Issue 35375: name shadowing while a module tries to import another - Python tracker (tricky examples)
- software assistance - Why am I getting "AttributeError" when running this Python function? - Matter Modeling Stack Exchange (a post that I saw which made me consider writing this here)
- python - Importing a library from (or near) a script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError - Stack Overflow (the stackoverflow canonical on the topic)
- me, 5 years ago, installing
flask
and trying to write my first webapp in a script calledflask.py
(admittedly, I wasn’t very experienced back then)
Would it be possible to have a warnings.warn
in the importer code that triggers if a module was imported as a local file from the current working directory with a second or third party module of the same name existing as well? It would have helped me 5 years ago, and I think most of the people who stumble over the same issue as well.
Just in case, an example of what I have in mind:
fastapi.py
import fastapi
app = fastapi.FastAPI()
...
On execution:
/home/dev/fastapi.py:1: UserWarning:
Importing local module /home/dev/fastapi.py that might shadow the installed module 'fastapi'.
Consider renaming local files in order to avoid name clashes.
warnings.warn("Importing local module {module_name} that might shadow the installed "
Traceback (most recent call last):
File "/home/dev/fastapi.py", line 1, in <module>
import fastapi
File "/home/dev/fastapi.py", line 3, in <module>
app = fastapi.FastAPI(
^^^^^^^^^^^^^^^
AttributeError: partially initialized module 'fastapi' has no attribute 'FastAPI' (most likely due to a circular import). Did you mean: 'fastapi'?