Skip to content

Type-narrowing of a list item for an inline list multiplied with a type-guard on said item #21099

@Avasam

Description

@Avasam

Feature

I would like the following to work:

from typing import assert_type

def _(foo: str | None) -> None:
    assert_type(["a", "b", foo] * bool(foo), list[str])

playground url: https://mypy-play.net/?gist=f6454b1662920bc8df00dfe047a80044

To my understanding, this would require 2 things that mypy currently doesn't do as shown by the above playground:

  1. Understanding bool is a truthyness typeguard. ie roughly treating bool(a) as: def bool[T](a: T | |Literal['', False, 0] | None) -> TypeGuard[T]: ...
  2. Doing type-narrowing on list.__mul__ with a type-guard.

Pitch

Let me quote @jaraco directly, as this is a pattern used a lot in his ecosystem (which includes setuptools): jaraco/jaraco.context#16 (comment)

I very much prefer to use algebraic expressions over branching logic. The expressiveness of multiplying by a bool is important to the aesthetic of simplicity here.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions