Repository navigation
Use the winning dataclass field type under multiple inheritance - #557
S (vexi1es) wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The base-hint logic still misclassifies diamond-inherited InitVar fields, allowing descendants to emit incompatible TypeScript inheritance without Omit or an error.
1 open issue
What changed in this PR
Aligns Python dataclass schemas with the winning field under multiple inheritance, following #547.
Changes:
- Uses field ownership to select annotations, resolve quoted types, and substitute generic arguments.
- Adds diamond-inheritance regression tests covering field types, base order, and InitVar projection.
| File | Description |
|---|---|
python/tests/test_dataclass_diamond_inheritance.py |
Adds inheritance and validation regression cases. |
python/src/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py |
Resolves schema types from the winning field’s declaring class. |
Review effort: Balanced
robgruen
left a comment
There was a problem hiding this comment.
Thank you for tracking down the difference between dataclass field selection and Python's annotation lookup. The comparison with Pydantic and the new descendant test are especially helpful. The original InitVar example is fixed. I reproduced two cases on df1e616 that I'd like to see addressed before merging: an undecorated subclass can still supply the wrong type, and an ordinary-field diamond that compiled on main now produces invalid TypeScript. I've left an example and a suggested regression check for each below.
| continue | ||
| if first is None: | ||
| first = base | ||
| if getattr(base, "__dataclass_fields__", {}).get(attr_name) is field: |
There was a problem hiding this comment.
Only a class with its own dataclass field table should count as the owner. getattr also finds an inherited table. That matters when a subclass reannotates a name without applying @dataclass again:
from dataclasses import InitVar, dataclass
@dataclass
class Root:
value: InitVar[int]
class Middle(Root): # intentionally not decorated
value: InitVar[str]
@dataclass
class Left(Middle):
pass
@dataclass
class Right(Middle):
value: InitVar[int]
@dataclass
class Diamond(Left, Right):
passThe winning Field is Root's. Middle didn't create one, but this identity check succeeds for Middle because it inherits Root's table. On main, the schema says Diamond.value is number; on this PR it says string. In both versions Pydantic accepts {"value": 42} and rejects {"value": "text"}.
Could we check the candidate class's own table (for example, vars(base).get("__dataclass_fields__", {})) and add this as a regression for both the emitted type and validation?
| def test_diamond_uses_the_type_of_the_winning_field( | ||
| target: type[Any], expected: str, accepted: object, rejected: object | ||
| ) -> None: | ||
| assert f" value: {expected};\n" in interface_body(target) |
There was a problem hiding this comment.
Could we also check that the whole ordinary-field interface compiles? I saw the note about leaving ordinary-field projection unchanged. Here's a case where the new field type makes that distinction observable: Root.value is int | str, Left(Root) inherits it, Right(Root) narrows it to str, and Diamond(Left, Right) declares no fields. All four are dataclasses.
Pydantic accepts {"value": 42}. The new property type is correct, so a property-line assertion passes, but the generated declaration is:
interface Diamond extends Left, Right {
value: number | string;
}The converter reports no errors, but tsc --strict --noEmit reports TS2430: Diamond incorrectly extends Right, whose value must be a string. On main the property was too narrow (string), but the declarations compiled.
Could we keep the corrected union and omit value from the conflicting base (for example, extends Left, Omit<Right, "value">)? A regression that compiles the emitted schema for this diamond would catch what the property assertion misses.
Only a class that holds the winning field in its own __dataclass_fields__ counts as its owner, so an undecorated subclass that reannotates a name no longer supplies its type. When a class inherits an ordinary field without redeclaring it and a base declares that name with a different field, the name is omitted from that base only, so the emitted interface compiles. The diamond tests also compile the emitted schemas with tsc. TypeScript is added to the Python dev dependencies and the Python CI job runs npm ci.
|
Thanks for the repro cases both are fixed now |
There was a problem hiding this comment.
🟡 Changes recommended
The projection incorrectly rejects agreeing fields from ordinary bases with a reserved-Omit error, causing valid schemas and TypeChatJsonTranslator construction to fail.
1 open issue
1 file not reviewed
python/package-lock.json: Generated file
Review effort: Balanced
A base that declares the name with its own field of the same type, after generic substitution, and the same requiredness does not conflict with the winning field, so it keeps its declaration. Unrelated bases that agree on a field keep the output they had before, including a schema type named Omit.
There was a problem hiding this comment.
🔵 Needs a closer look
Comparing raw Python annotations instead of emitted TypeScript types triggers unnecessary base projections for equivalent properties, causing otherwise valid dataclasses or generic parameters named Omit to fail schema conversion.
No open issues 🎉
1 resolved since last review
1 file not reviewed
python/package-lock.json: Generated file
Review effort: Balanced


This follows up on the review comment left on #547 after it was approved.
Problem
With multiple inheritance, the Python schema can show a type that validation rejects.
Childis declared withvalue: string, butChild.__dataclass_fields__["value"]is theInitVar[int]field and Pydantic accepts1and rejects"text". The same happens with an ordinary field in place of theInitVar, so this is not specific to #547.Cause
The converter reads field types from
get_type_hints(py_type), which follows the MRO and finds the annotation inRightfirst.@dataclassworks differently: it takes every field of the first base, including the ones that base only inherits, soLeftbrings in the field fromBaseand it wins overRight.Change
_field_ownersmaps each field to the class that created the winning field: the class that annotates the name and holds that field object in its own__dataclass_fields__. Inherited fields are the same objects in every subclass, so the lookup is an identity check. A subclass that is not decorated only reaches its base's table through attribute lookup, so it is not treated as the owner when it reannotates a name.InitVartype, and the generic substitution all come from that class.InitVarand projects it away withOmit.interface Diamond extends Left, Omit<Right, "value">. The winning type need not satisfy the other base's declaration, and without this the emitted interface did not compile. A base whose field has the same type, after generic substitution, and the same requiredness as the winning one is left as it is, so unrelated bases that agree on a field keep the output they had before.Omitname now say "dataclass inheritance" instead of "InitVar inheritance", since ordinary fields can needOmittoo.Tests
python/tests/test_dataclass_diamond_inheritance.pycovers anInitVar, an ordinary field, a narrowed union field, both base orders, a generic base, a quoted type, an undecorated intermediate class and a descendant that redeclares the field, and compares the result with Pydantic validation. It also checks that bases which agree on a field, including through a generic base, get noOmit, while a base whose field is required where the winning one has a default does.It also compiles the emitted schemas of the diamonds with
tsc --strict --noEmit. For that,typescript(^7.0.2, the same range as the TypeScript package) is added to the dev dependencies inpython/package.json, and the Python CI job runsnpm cibefore the tests. Locally the compile test is skipped when TypeScript is not installed.Full suite: 895 passed and 3 skipped on Python 3.11, 898 passed on Python 3.14, Pyright reports 0 errors.
Not changed
When a class redeclares an ordinary field with a type that is not assignable to the base's, for example
value: strovervalue: int, the interface still extends the base unchanged andtscreports TS2430, as onmain. Narrowing overrides such as aLiteraltag compile fine, so I left that alone to keep this change small.