python / python/mypy

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

Open
#21,099 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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): https://github.com/jaraco/jaraco.context/pull/16#discussion_r2967882086

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy playground and reproduce the assert_type example. Investigate the two requested behaviors—truthiness narrowing through bool(foo) and narrowing the element type of an inline list multiplied by that guard—and consider the issue complete when the example is accepted with list[str] as asserted.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.