Skip to content

Regression: dict | None or dict fallback breaks type inference for nested dicts after PR #19249 #19492

@KevinRK29

Description

@KevinRK29

Bug Report

After upgrading mypy past PR #19249, we observed new errors related to dictionary fallback using or expressions when value types are unions of nested dicts and optional types.

This appears to be a regression in type inference, as the same code passed in previous versions of mypy.

To Reproduce

from typing import Union, Optional, Any

P = dict[str, Union[Optional[str], dict[str, Optional[str]]]]

def f(x: P) -> None:
    pass

def g(x: dict[str, Any] | None, s: str | None) -> None:
    f(x or {'x': s})  # ❌ Error in master branch, passes in latest mypy release (1.17.0)

mypy playground Gist: https://mypy-play.net/?mypy=master&python=3.12&gist=c4a5711c815d342425983850913896fe

Actual Behavior

main.py:9: error: Argument 1 to "f" has incompatible type "dict[str, Any] | dict[str, str | None]"; expected "dict[str, str | dict[str, str | None] | None]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.18.0+dev.abb1cc787455501e43f344c8af2de7d0d262e5ef
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions