Skip to content

variance okay for literals, but not expressions ([1, 2] okay for list[int | None] but [1] + [2] is error) #16623

Open
@kurtbrose

Description

@kurtbrose
a: list[int | None] = [1] + [2] + [None]
b: list[int | None] = [1] + [2]
c: list[int | None] = [1, 2]

a is okay, b is an error, c is okay

Apologies if this is a repeat / common issue. I couldn't find anything in the docs. This is popping up for me a lot, my interpretation is that mypy allows type invariance on literals that it will not for expressions.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=b999a1bd2e975645b868c0b376c910e8

Expected Behavior

Either b and c should both be errors or (preferably) neither.

Actual Behavior

b is an error but c isn't

Your Environment

  • Mypy version used: 1.7.1 and master
  • Python version used: 3.11

Activity

glenrobertson

glenrobertson commented on Dec 5, 2023

@glenrobertson

+1 also experiencing this issue! any help would be greatly appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

        Participants

        @glenrobertson@kurtbrose@JelleZijlstra

        Issue actions

          variance okay for literals, but not expressions ([1, 2] okay for list[int | None] but [1] + [2] is error) · Issue #16623 · python/mypy