typing
typing copied to clipboard
Allow `NotRequired[]` to be passed as a `TypeVar`
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.
I am not sure I understand what you are trying to achieve here. NotRequired is currently only applicable to TypedDict fields and have no meaning outside them.
I want to define a TypedDict class where the necessity of a field (whether it's required or not required) depends on a type variable, so that I do not have to define a bunch of classes twice.
Yes I know that passing NotRequired via a TypeVar into a TypedDict doesn't work currently, however I was under the impression that this issue tracker can be used to suggest improvements to the typing module.