python / python/mypy

MyPy Incorrectly Flags Module Attribute Inside Format String

Open
#9,646 0 comments 0 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

An unexpected [attr-defined] was reported when accessing module attributes inside of a format string.

To Reproduce

  1. Create a file called constants.py with contents below:
FOO = "foo"
  1. Create a file called main.py with contents below:
import constants

def bar():
    # type: () -> str
    print("{foo}".format(foo=constants.FOO))
    return "{constants.FOO}".format(constants=constants)
  1. run python3 -m mypy constants.py main.py
main.py:6: error: Module has no attribute "FOO"
Found 1 error in 1 file (checked 2 source files)

Expected Behavior

I expected the format string "{constants.FOO}".format(constants=constants) to not throw an error, since constants.FOO is defined.

(Write what you thought would happen.)

Actual Behavior

The line print("{foo}".format(foo=constants.FOO)) reports no error (indicating that the value FOO exists in constants, but the line "{constants.FOO}".format(constants=constants) reports an error as if it does not.

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: python3 -m mypy constants.py main.py
  • Mypy configuration options from mypy.ini (and other config files): No mypy.ini used
  • Python version used: Python 3.8.5 (brew installed)
  • Operating system and version: MacOS Catalina 10.15.6

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

Start with the constants.py and main.py reproducer and run python3 -m mypy constants.py main.py using the reported example. Trace how the format-string expression is analyzed, then verify that the module attribute inside the format string no longer produces an attr-defined error while the existing direct access remains valid.

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
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.