Skip to content

Empty collection not narrowing type for aesthetic oneliners #11400

@decimatedTomato

Description

@decimatedTomato

I recently came across two scenarios where pyright in strict mode makes it hard to write a oneliner.

  1. Optionally add an element into a collection
  2. Merging a list of collections into one large collection
# pyright: strict
optional = True
a = {"a", "b"} | {"c"} if optional else set()
b = set().union({"a"}, {"b"}, {"c"})

There is a type mismatch is the same in both cases:
An empty set has type set[Unknown] but these are temporary objects so the unknown can never become a problem. Mypy for example doesn't care about this.

I would find it nice if this was accepted by pyright.
I found a work around for case 2 but not case 1.

from itertools import chain
b = set(chain(({"a"}, {"b"}, {"c"}))

I would understand if this doesn't make sense for pyright because the type checker encourages more explicit code, in this case the problem would be solved by simply using an if statement and spreading the logic over several lines. I wouldn't want to add complexity to the project. I don't know how pyright works internally but I thought maybe supporting this use case would be beneficial in more ways I can't see.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions