Skip to content

Use the winning dataclass field type under multiple inheritance - #557

Open
S (vexi1es) wants to merge 4 commits into
microsoft:mainfrom
vexi1es:python-initvar-diamond
Open

S (vexi1es) wants to merge 4 commits into
microsoft:mainfrom
vexi1es:python-initvar-diamond

Conversation

@vexi1es

@vexi1es S (vexi1es) commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

@dataclass
class Base:
    value: InitVar[int]

@dataclass
class Left(Base):
    pass

@dataclass
class Right(Base):
    value: InitVar[str]

@dataclass
class Child(Left, Right):
    pass

Child is declared with value: string, but Child.__dataclass_fields__["value"] is the InitVar[int] field and Pydantic accepts 1 and rejects "text". The same happens with an ordinary field in place of the InitVar, 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 in Right first. @dataclass works differently: it takes every field of the first base, including the ones that base only inherits, so Left brings in the field from Base and it wins over Right.

Change

  • _field_owners maps 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.
  • The field type, the namespace used to resolve a quoted InitVar type, and the generic substitution all come from that class.
  • The hints of the base classes go through the same lookup, so a class that extends such a diamond and redeclares the field sees the winning InitVar and projects it away with Omit.
  • 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, for example 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.
  • The merged annotations are still used whenever both lookups agree, so nothing changes without this kind of inheritance. Type hints of another class are resolved at most once per class.
  • The two error messages about the Omit name now say "dataclass inheritance" instead of "InitVar inheritance", since ordinary fields can need Omit too.

Tests

python/tests/test_dataclass_diamond_inheritance.py covers an InitVar, 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 no Omit, 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 in python/package.json, and the Python CI job runs npm ci before 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: str over value: int, the interface still extends the base unchanged and tsc reports TS2430, as on main. Narrowing overrides such as a Literal tag compile fine, so I left that alone to keep this change small.

Copilot AI balanced review requested due to automatic review settings December 3, 2026 11:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Copilot AI balanced review requested due to automatic review settings December 3, 2026 11:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the changes aligning schema field types with dataclass field selection under multiple inheritance.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@robgruen robgruen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):
    pass

The 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Copilot AI balanced review requested due to automatic review settings December 5, 2026 08:51
@vexi1es

Copy link
Copy Markdown
Contributor Author

Thanks for the repro cases both are fixed now
The owner check uses only the class's own field table so an undecorated subclass no longer gives the type
For a plain field the diamond now omits value only from the base whose field lost
Added tests for both plus a test that compiles the emitted schemas with tsc strict and the Python CI job now runs npm ci so it runs there
If you'd rather not add typescript to the Python CI I can drop that part

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.
Copilot AI balanced review requested due to automatic review settings December 5, 2026 09:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants