Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Add more specific error message when file has same name as an imported module #95754

Copy link
Copy link
Closed
@janine9vn

Description

@janine9vn
Issue body actions

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancementA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.