mypy icon indicating copy to clipboard operation
mypy copied to clipboard

`str` assignment to recursive `Sequence[...] | int` should fail

Open kbouchiat opened this issue 2 years ago • 1 comments

Bug Report

No error is raised when assigning a str to a recursive alias of the form Alias = Sequence[Alias] | int. This is likely due to str being itself an instance of typing.Sequence[str].

To Reproduce

from collections.abc import Sequence
from typing import TypeAlias

RecursiveListA: TypeAlias = "list[RecursiveListA] | int"
RecursiveListB: TypeAlias = "Sequence[RecursiveListB] | int"
RecursiveListC: TypeAlias = "Sequence[RecursiveListC] | str"

# E: Incompatible types in assignment (expression has type "str", variable has type "RecursiveListA")
a: RecursiveListA = 'a'

# Missing error?
b: RecursiveListB = 'b'

# E: List item 0 has incompatible type "int"; expected "Sequence[RecursiveListC]"
c: RecursiveListC = [0]

https://mypy-play.net/?mypy=master&python=3.12&gist=5fbb09454047fdaea0a4851c0832d63f

Expected Behavior

Expected assignment error for assignment to b with type RecursiveListB on line 12.

Actual Behavior

No error is raised for the assignment on line 12.

main.py:9: error: Incompatible types in assignment (expression has type "str", variable has type "RecursiveListA")  [assignment]
main.py:15: error: List item 0 has incompatible type "int"; expected "Sequence[RecursiveListC]"  [list-item]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used:
    • master (cbbcdb8a2)
    • 1.7.1
  • Mypy command-line flags:
    • N/A
  • Mypy configuration options from mypy.ini (and other config files):
    • N/A
  • Python version used:
    • Python 3.12.0

Additional Notes

My lead is that is_subtype incorrectly assumes that builtins.str <: Union[typing.Sequence[...], builtins.int] inside of the call to check_type_parameter in the nominal check of SubtypeVisitor.visit_instance, since the pair is stored in the "assuming" stack by an upstream is_subtype call.

https://github.com/python/mypy/blob/cbbcdb8a2c0fb70f3b89a518b7aa36925d9c4c37/mypy/subtypes.py#L159-L178

This nominal check happens since builtins.str (left) has base type of typing.Sequence (right), which is not the case for either RecursiveListA and/or RecursiveListC.

https://github.com/python/mypy/blob/cbbcdb8a2c0fb70f3b89a518b7aa36925d9c4c37/mypy/subtypes.py#L523

kbouchiat avatar Dec 12 '23 10:12 kbouchiat

However surprising, this behavior is technically correct because str is subtype of Sequence[str]. (to understand more, try writing code that will crash at runtime)

ilevkivskyi avatar Jan 12 '24 09:01 ilevkivskyi