Skip to content

Commit

Permalink
Add support for NotRequired generics in TypedDict (#7932)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Oct 26, 2023
1 parent aa73451 commit 064b24c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pydantic/_internal/_generics.py
Expand Up @@ -311,7 +311,8 @@ 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]
# NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below
return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]

# We handle pydantic generic models separately as they don't have the same
# semantics as "typing" classes or generic aliases
Expand Down
20 changes: 20 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,20 @@ 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]

ta_foo_str = TypeAdapter(FooStr)
assert ta_foo_str.validate_python({'type': 'tomato'}) == {'type': 'tomato'}
assert ta_foo_str.validate_python({}) == {}
ta_foo_generic = TypeAdapter(FooGeneric[str])
assert ta_foo_generic.validate_python({'type': 'tomato'}) == {'type': 'tomato'}
assert ta_foo_generic.validate_python({}) == {}

0 comments on commit 064b24c

Please sign in to comment.