A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/python/cpython/issues/95754 below:

Add more specific error message when file has same name as an imported module · Issue #95754 · python/cpython · GitHub

Feature / enhancement

Currently, if a python file I create and am trying to run has the same name as a module I'm importing in it (i.e. my file is named random.py and I try to do import random; print(random.randint(5)), the following error message appears:

AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)

Instead, for this particular scenario, a more specific error message would be helpful:

ImportError: random.py imported itself. File name should be different than the imported module name.
Pitch

Frequently, someone learning python will try to name their python files after the topic they are learning about. These topics can be about a specific module (e.g. random, turtle, pygame, requests). For instance, someone experimenting with the turtle module, might name their python file turtle.py. This results in the scenario of a person trying to import a module, but instead their program tries to import itself because of the name collision.

The current error message isn't clear that the issue is the filename conflicting with the module name and overriding it. Folks with more experience can deduce that from the "circular import" portion, but beginners are often confused by the "AttributeError" portion. I think this scenario would be a good candidate for a more specific error message, to better warn about this common pitfall.

The recent improvements for more detailed and specific error messages have helped many people, especially those new to Python. I think this would be a worthwhile addition in that same vein.

Considerations & discussion points

The example improved error message I have above is very much open to improvements, if folks have suggestions.
I am also operating under the somewhat informed assumption that there isn't a valid case for a file to import itself, so there would not be an issue with this error appearing if the imported module is the same name as the file itself.

Previous discussion Linked PRs

ionite34, ichard26, Xithrius, D0rs4n, GDWR and 4 more


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4