False negative when declaring a class with a literal string base, which could refer to a forward-reference type alias
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
mypy interprets a literal string, which could refer to a forward-reference type alias, as a valid class base.
To Reproduce
The following example uses both a forward reference (class B1("A")) and a string which doesn't refer to anything (class B2("D")):
class B1("A"):
pass
b1: B1 = B1()
b1.a = "" # mypy: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
class B2("D"): # mypy: Class cannot subclass value of type "Any" [misc] \
# mypy: Name "D" is not defined [name-defined]
pass
class A:
a: int
Expected Behavior
I expect the following snippet to show up if we're not under a typing.TYPE_CHECKING block:
class B1("A"): # mypy: Invalid base class "A" [misc] \
# mypy: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases \
# mypy: Variable "A" is not valid as a type [valid-type]
pass
EDIT: this is a more sensible expected error:
class B1("A"): # mypy: Invalid base class [misc]
pass
I can't gauge from PEP 613 whether or not this should should be OK (mypy doesn't show any errors, but FWIW pylance or pyright sees this as an error):
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
class B("A"): # pylance: Expected class type but received "Literal['A']" \
# pylance: Base class type is unknown, obscuring type of derived class
pass
class A:
pass
Your Environment
Tested on mypy-play.net:
- Mypy version used: 0.981 and
master - Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):show_error_codes = True - Python version used: 3.10
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two class-base examples on mypy-play.net with mypy 0.981 or master and no command-line flags. Compare diagnostics for the forward-reference and unresolved literal-string bases, then determine the intended behavior outside and inside TYPE_CHECKING; done means the relevant cases report the agreed invalid-base error without regressing valid forward references.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100