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

Fix strict-optional in extending generic TypedDict #16398

Merged
merged 1 commit into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion mypy/semanal_typeddict.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
has_placeholder,
require_bool_literal_argument,
)
from mypy.state import state
from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type
from mypy.types import (
TPDICT_NAMES,
Expand Down Expand Up @@ -203,7 +204,8 @@ def add_keys_and_types_from_base(
any_kind = TypeOfAny.from_error
base_args = [AnyType(any_kind) for _ in tvars]

valid_items = self.map_items_to_base(valid_items, tvars, base_args)
with state.strict_optional_set(self.options.strict_optional):
valid_items = self.map_items_to_base(valid_items, tvars, base_args)
for key in base_items:
if key in keys:
self.fail(f'Overwriting TypedDict field "{key}" while merging', ctx)
Expand Down
17 changes: 17 additions & 0 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -3379,3 +3379,20 @@ bar |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "Di
bar |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "Dict[int, str]"; expected "TypedDict({'key'?: int, 'value'?: str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testGenericTypedDictStrictOptionalExtending]
from typing import Generic, TypeVar, TypedDict, Optional

T = TypeVar("T")
class Foo(TypedDict, Generic[T], total=False):
a: Optional[str]
g: Optional[T]

class Bar(Foo[T], total=False):
other: str

b: Bar[int]
reveal_type(b["a"]) # N: Revealed type is "Union[builtins.str, None]"
reveal_type(b["g"]) # N: Revealed type is "Union[builtins.int, None]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]