python / python/mypy

Support generic upper bounds

Open
#20,293 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

Allow generic upper bounds such as:

class ClassA[T, S: Sequence[T]]: ...

Pitch

PEP 695 has an example that currently doesn't work, and alludes to a future extension to the typesystem that eliminates the limitation:

# The following generates no compiler error, but a type checker
# should generate an error because an upper bound type must be concrete,
# and ``Sequence[S]`` is generic. Future extensions to the type system may
# eliminate this limitation.
class ClassA[S, T: Sequence[S]]: ...

I ran into a usecase for this that I have no way of expressing with the current generics limitations, and generic upper bounds would solve it. I will provide a simpler version of it here so it's easier to discuss.

from typing import Callable, Iterable, Sequence

type CostFunction[T] = Callable[[T], float]

# Sequence[T] gives an error, because T is not concrete
def get_lowest_cost_sequence[T, S: Sequence[T]](
    seqs: Iterable[S], item_cost: CostFunction[T]
) -> S:
    def seq_cost(seq: S) -> float:
        return sum(item_cost(t) for t in seq)

    return sorted(seqs, key=seq_cost)[0]

In the example, we are working with sequences, and a cost function for each item in the sequences. The crux is that the function must return the same type as the original sequences. In other words this is an incorrect type signature:

# Return type Sequence[T] is looser, because it does not mean whatever is
# returned will be _the same type_ as what is passed in. Any users of this
# function would have to cast the result for it to expose the same functionality
# as what was in `seqs`.
def get_lowest_cost_sequence[T](
    seqs: Iterable[Sequence[T]], item_cost: CostFunction[T]
) -> Sequence[T]:
    ...

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

No implementation files, tests, or entry points are named. Start with the PEP 695 type-parameter-scopes section and the examples in this issue, then trace mypy's handling of generic upper bounds; done means valid generic bounds are accepted while invalid non-concrete bounds remain rejected, with regression coverage.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.