Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for NotRequired generics in TypedDict #7932

Merged
merged 2 commits into from Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion pydantic/_internal/_generics.py
Expand Up @@ -311,7 +311,7 @@ def replace_types(type_: Any, type_map: Mapping[Any, Any] | None) -> Any:
# We also cannot use isinstance() since we have to compare types.
if sys.version_info >= (3, 10) and origin_type is types.UnionType:
return _UnionGenericAlias(origin_type, resolved_type_args)
return origin_type[resolved_type_args]
return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved

# We handle pydantic generic models separately as they don't have the same
# semantics as "typing" classes or generic aliases
Expand Down
16 changes: 16 additions & 0 deletions tests/test_generics.py
Expand Up @@ -35,8 +35,10 @@
from typing_extensions import (
Annotated,
Literal,
NotRequired,
OrderedDict,
ParamSpec,
TypedDict,
TypeVarTuple,
Unpack,
get_args,
Expand All @@ -53,6 +55,7 @@
PositiveInt,
PydanticSchemaGenerationError,
PydanticUserError,
TypeAdapter,
ValidationError,
ValidationInfo,
computed_field,
Expand Down Expand Up @@ -2849,3 +2852,16 @@ def test_mix_default_and_constraints() -> None:

class _(BaseModel, Generic[T]):
x: T


def test_generic_with_not_required_in_typed_dict() -> None:
T = TypingExtensionsTypeVar('T')

class FooStr(TypedDict):
type: NotRequired[str]

class FooGeneric(TypedDict, Generic[T]):
type: NotRequired[T]

assert TypeAdapter(FooStr)
assert TypeAdapter(FooGeneric[str])
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved