Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Fix optional fields of inherited models becoming required in the generated `types.py`. TypedDict subclasses are now declared with `total=False`, like base TypedDicts, because totality is not inherited. Required fields are still marked with `Required[...]`.
Original file line number Diff line number Diff line change
Expand Up @@ -362,13 +362,17 @@ def declare_model(self, model: ModelType) -> str:

Uses functional form when any property wire_name is a Python keyword
(e.g. 'and', 'class') since keywords can't be identifiers in class bodies.

Subclasses also get ``total=False``: TypedDict totality is not inherited and only applies
to the keys declared in that class body, so without it every optional field a subclass adds
would become required. Required fields are always wrapped in ``Required[...]``.
"""
if self.has_keyword_wire_names(model):
return "" # functional form is rendered separately
non_discriminated_parents = [p for p in model.parents if not p.discriminated_subtypes]
if non_discriminated_parents and not self.needs_flat_typeddict(model):
basename = ", ".join([m.name for m in non_discriminated_parents])
return f"class {model.name}({basename}):{model.pylint_disable()}"
return f"class {model.name}({basename}, total=False):{model.pylint_disable()}"
return f"class {model.name}(TypedDict, total=False):{model.pylint_disable()}"

def declare_functional_model(self, model: ModelType) -> str:
Expand Down
42 changes: 41 additions & 1 deletion packages/http-client-python/tests/unit/test_typeddict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,47 @@ def test_typeddict_inheritance_without_requiredness_change_still_subclasses():

env = _make_env()
output = TypesSerializer(code_model=code_model, env=env, models=[parent, child]).serialize()
assert "class Derived(Base):" in output
assert "class Derived(Base, total=False):" in output


def test_typeddict_subclass_keeps_own_optional_fields_optional():
"""Optional fields declared on a TypedDict subclass must stay optional.

TypedDict totality is not inherited: without ``total=False`` on the subclass, every field it
declares becomes required, so partial request dicts fail type checking (issue #12625).
Required fields must stay required via ``Required[...]``.
"""
code_model = _make_code_model(models_mode="dpg")
str_type = build_type({"type": "string"}, code_model)

parent = _make_model_with_usage(code_model, "Base", 2, DPGModelType)
parent.is_typed_dict_only = True
parent.properties = [_make_typed_property(code_model, "id", str_type, optional=True)]

child = DPGModelType(
yaml_data={"name": "Derived", "type": "model", "snakeCaseName": "derived", "usage": 2},
code_model=code_model,
properties=[
parent.properties[0], # inherited unchanged
_make_typed_property(code_model, "location", str_type, optional=True),
_make_typed_property(code_model, "kind", str_type, optional=False),
],
parents=[parent],
)
child.is_typed_dict_only = True
code_model.model_types = [parent, child]

env = _make_env()
output = TypesSerializer(code_model=code_model, env=env, models=[parent, child]).serialize()
assert "class Derived(Base, total=False):" in output
assert "location: str" in output
assert "kind: Required[str]" in output

namespace: dict = {}
exec(compile(output, "types.py", "exec"), namespace) # pylint: disable=exec-used
derived = namespace["Derived"]
assert derived.__required_keys__ == frozenset({"kind"})
assert derived.__optional_keys__ == frozenset({"id", "location"})


# ---------- Bug 1: internal enum reference/import in types.py (issue #11626) ----------
Expand Down
Loading