python / python/mypy

Don't issue `no-redef` with conditional imports

Open
#13,914 5 comments 18 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When an exception is caught from a block with a single import statement, one can be certain that the import failed (right?).

When an import fails, a to-be-imported function is not defined.

If a function is not defined, mypy should not issue a no-redef message.

To Reproduce

pip install overrides

"""Feature request: detect failed imports and suppress no-redef."""
try:
    from overrides import overrides
except ModuleNotFoundError:
    # mypy issues no-redef
    def overrides() -> None:
        pass

print(overrides)

Expected Behavior

No message

Actual Behavior

bug.py:5: error: Name "overrides" already defined (possibly by an import) [no-redef]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.982 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.8

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue's snippet with mypy 0.982 on Python 3.10.8, using the default configuration and no command-line flags. Trace how the conditional import and fallback definition are analyzed; done when this case no longer reports no-redef without introducing regressions in existing checks.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.