python / python/typing

Allow `NotRequired[]` to be passed as a `TypeVar`

Open
#1,323 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

I just found myself wanting to do the following:

from typing import TypedDict, NotRequired, Generic, TypeVar, Union, Never

_T = TypeVar('_T')

Foo = Union['FooSub1[_T]', 'FooSub2[_T]', 'FooSub3[_T]']

class BaseFoo(TypedDict, Generic[_T]):
    bar: _T

class FooSub1(BaseFoo[_T]):
    sub1: str

class FooSub2(BaseFoo[_T]):
    sub2: str

class FooSub3(BaseFoo[_T]):
    sub3: str

def foo(foo_with_bar: Foo[int]):
    reveal_type(foo_with_bar) # Type of "foo_with_bar" is "FooSub1[int] | FooSub2[int] | FooSub3[int]"

def bar(foo_without_bar: Foo[NotRequired[Never]]): # error: "NotRequired" is not allowed in this context
    pass

Mypy and Pyright both disallow NotRequired to be passed as a TypeVar. However the only way to avoid doing that would require me to duplicate all subclass definitions, which I am not willing to do because I have more than a dozen and so much duplication would make the code less maintainable.

Contributor guide

No contributing guide indexed for this repository

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 reproducer in the issue and compare the current NotRequired and TypeVar rules in mypy and Pyright, the two checkers named in the report. No files or tests are identified; done would require an agreed typing-rule design and corresponding checker behavior without duplicating the TypedDict subclasses.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
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.