Skip to content

Recursive types not working correctly #13786

@Waszker

Description

@Waszker

Bug Report

Related to #731
The new recursive types support (enabled by flag --enable-recursive-aliases) does not behave correctly.

To Reproduce

from typing import Dict, List, Union

JSON = Union[Dict[str, 'JSON'], List['JSON'], str, int, float, bool, None]

some_data = {'eggs': 'spam'}
json_data: JSON = {'foo': 'bar', 'python': some_data}

Expected Behavior

The MyPy should not detect any errors since some_data is a valid JSON representation and can be safely nested in another JSON.

Actual Behavior

$ mypy --enable-recursive-aliases main.py                                                                                                                                                                        
main.py:6: error: Dict entry 1 has incompatible type "str": "Dict[str, str]"; expected "str": "Union[Dict[str, JSON], List[JSON], str, float, None]"
Found 1 error in 1 file (checked 1 source file)

Please note that explicitly marking some_data as JSON does not return the error, e.g.

from typing import Dict, List, Union

JSON = Union[Dict[str, 'JSON'], List['JSON'], str, int, float, bool, None]

some_data: JSON = {'eggs': 'spam'}
json_data: JSON = {'foo': 'bar', 'python': some_data}  # no error detected

Your Environment

  • Mypy version used: 0.981
  • Mypy command-line flags: --enable-recursive-aliases
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions