Skip to content

Include dataclass InitVar fields in Python prompt schemas - #547

Merged
robgruen merged 5 commits into
microsoft:mainfrom
vexi1es:python-dataclass-initvar
Dec 2, 2026
Merged

robgruen merged 5 commits into
microsoft:mainfrom
vexi1es:python-dataclass-initvar

Conversation

@vexi1es

@vexi1es S (vexi1es) commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

A dataclass that uses InitVar cannot be used with TypeChatJsonTranslator, and its prompt schema describes the field as any.

from dataclasses import InitVar, dataclass
from typechat import TypeChatValidator, python_type_to_typescript_schema

@dataclass
class Repeated:
    name: str
    repeat: InitVar[int]

    def __post_init__(self, repeat: int) -> None:
        self.name = self.name * repeat

result = python_type_to_typescript_schema(Repeated)
print(result.typescript_schema_str)
# interface Repeated {
#     name: string;
#     repeat: any;
# }
print(result.errors)
# ["'dataclasses.InitVar[int]' cannot be used as a type annotation."]

validator = TypeChatValidator(Repeated)
print(validator.validate_object({"name": "ab"}))
# Failure: Validation path `repeat` failed ... Field required
print(validator.validate_object({"name": "ab", "repeat": 2}))
# Success(value=Repeated(name='abab'))

The validator already treats repeat as a required integer, because it is a constructor argument. The schema conversion did not recognise InitVar, so it reported an error and fell back to any; with the default _raise_on_schema_errors, constructing a TypeChatJsonTranslator for the class raises.

Change

When walking dataclass fields, InitVar[T] is unwrapped to T (a bare InitVar becomes any) before the property is declared, so the field is emitted with its real type, optionality and comment. This follows the ClassVar handling added in #533: the emitted properties again match what the validator accepts.

Following review, the InitVar path also:

  • resolves quoted types inside InitVar[...], including a class defined inside a function and the type parameters of a generic class; a name that cannot be resolved is reported in result.errors with the field and the name;
  • leaves an InitVar that a subclass does not redeclare to the base interface, so a concrete subclass of a generic dataclass gets it with the base's type arguments;
  • omits an InitVar that field(init=False) takes out of the constructor when it has no default;
  • reports a schema error when a subclass makes a required base property optional, or removes a base property (by taking it out of the constructor, inheriting such an exclusion from another base, or replacing it with a ClassVar), because the derived interface cannot express that; all bases are checked, and a required inherited InitVar is declared on the subclass when another base has it as optional;
  • resolves the type hints of each base once per class, so the compatibility check adds no per-field get_type_hints calls.

Tests

python/tests/test_dataclass_initvars.py covers required, defaulted, Annotated, inherited, bare, quoted, local and generic InitVars, the init=False cases, representable and unrepresentable overrides, and an unresolved quoted type. For the representable cases the properties of the whole interface chain, and which of them are required, are compared with pydantic's JSON schema. A translation is run through a mocked model.

Rebased on main after #549. Ran from python/ on Windows:

  • pytest: 856 passed, 3 skipped on Python 3.11; 859 passed on Python 3.14
  • npx pyright: 0 errors

Copilot AI balanced review requested due to automatic review settings November 26, 2026 19:05

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

Quoted wrapped annotations such as InitVar["int"] remain unresolved, causing conversion to emit any with a schema error and default translator construction to raise.

1 open issue
What changed in this PR

This PR extends Python prompt-schema generation to include dataclass InitVar constructor arguments, aligning emitted fields with validator inputs and complementing the earlier ClassVar handling.

Changes:

  • Unwraps InitVar[T] to its underlying type and maps bare InitVar to any.
  • Adds six regression cases covering defaults, annotations, inheritance, schema properties, and translation with a mocked model.
File Description
python/​tests/​test_dataclass_initvars.py Adds schema and translator regression tests for InitVar fields.
python/​src/​typechat/​_internal/​ts_conversion/​python_type_to_ts_nodes.py Unwraps dataclass InitVar annotations before property conversion.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 19:31

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

Schema conversion fails with NameError for factory-local self-referential dataclasses because the declaring class’s name is missing from localns.

1 open issue
1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 27, 2026 16:42

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

Quoted generic InitVar annotations can raise NameError because the resolution namespace omits the declaring class’s type parameters, requiring a namespace fix and regression coverage.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Resolve quoted InitVar types in generic dataclasses

python/​src/​typechat/​_internal/​ts_conversion/​python_type_to_ts_nodes.py:233

Quoted generic InitVar types raise NameError because this namespace omits the declaring class's type parameters. This affects function-local Generic[T] dataclasses with value: InitVar["T"], as well as Python 3.12+ class Box[T] declarations. Include __type_params__ with a fallback to __parameters__ in localns, and add regression coverage for quoted generic types.

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 28, 2026 15:04

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

Human assessment is needed because a concrete generic dataclass subclass can emit an undeclared type parameter in its TypeScript schema without reporting a schema error.

No open issues 🎉

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.

Thanks S (@vexi1es) for this contribution! Including InitVar constructor inputs is a useful schema/validation alignment fix, and the mocked translator coverage and follow-up work on quoted, local, and generic annotations are appreciated.

I reproduced two remaining correctness cases at a82997c77a94692b0788fbbe59974439f7cb511d that I would like addressed before merging.

Both underlying limitations also exist for ordinary dataclass fields today. The concern here is that this PR newly accepts these InitVar cases with an empty schema-error list, whereas they were previously reported as unsupported. I am asking for focused handling of the new InitVar path, not a general dataclass or generic-type rewrite.

1. Concrete generic subclasses can emit an undeclared type parameter

For example:

from dataclasses import InitVar, dataclass, field
from typing import Generic, TypeVar

T = TypeVar("T")

@dataclass
class Box(Generic[T]):
    name: str
    value: InitVar["T"]

@dataclass
class IntBox(Box[int]):
    pass

The generated schema contains:

interface IntBox extends Box<number> {
    name: string;
    value: T;
}

IntBox does not declare T; the separate Box<T> declaration does not make that parameter available in the derived interface. Conversion nevertheless returns errors=[], allowing an invalid schema into the translator's prompt. The relevant path is the InitVar resolution and property declaration.

Proposed direction: before unwrapping, avoid redeclaring unchanged inherited InitVar properties and let the parameterized base interface supply their types. The existing base-attribute comparison looks reusable, combined with a check that the subclass has not explicitly redeclared the field. Please preserve explicit subclass overrides, including changes to defaults and optionality. That should avoid introducing general-purpose type-variable substitution.

2. An InitVar excluded from initialization can still become required

@dataclass
class NotInConstructor:
    name: str
    value: InitVar[int] = field(init=False)

For this no-default case, conversion emits a required value: number property with errors=[]. However, Pydantic's JSON-schema properties contain only name, and TypeChatValidator(NotInConstructor).validate_object({"name": "ab"}) succeeds without value. The prompt schema therefore advertises a required input that the validator does not require. See the dataclass field-processing loop.

Proposed direction: omit InitVar fields excluded with init=False when they have no default. Please do not blanket-skip every init=False field: Pydantic can still include defaulted ones, so preserve that distinction.

Regression coverage and verification

Please add regressions for:

  • A concrete subclass of a generic dataclass with an inherited InitVar, checking that its own interface has no undeclared type parameter.
  • The excluded, no-default InitVar case, comparing the emitted properties with Pydantic's schema.
  • A defaulted init=False counterpart and an explicit subclass default/optionality override, to guard against over-filtering.

I ran 55 focused dataclass and schema-conversion tests on Python 3.14; all passed, so the existing suite does not catch these cases. I separately reproduced the two cases above. I did not rerun Pyright or the full Python-version matrix, and the proposed fix directions have not yet been implemented or tested. The Python and Node CI runs for this head currently show action_required, with no jobs executed, so normal CI validation is still outstanding.

These look like small, localized corrections rather than a change in direction. Thanks again for working through the annotation edge cases.

Review prepared with Copilot assistance.

Copilot AI balanced review requested due to automatic review settings November 29, 2026 21:24
@vexi1es

Copy link
Copy Markdown
Contributor Author

Thanks for looking into this, pushed a fix for both cases and added the tests you listed, checked on 3.11 and 3.14

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

Human assessment is needed because an inheritance edge case can leave generated TypeScript requiring an input excluded from the child’s constructor.

No open issues 🎉

Review effort: Balanced

@robgruen

Copy link
Copy Markdown
Contributor

Thanks, S (@vexi1es). I rechecked 40219dc: the concrete generic subclass now gets its inherited InitVar from the parameterized base, and the standalone init=False case matches Pydantic. The full Python suite passed locally on 3.11 (763 passed, 3 skipped) and 3.14 (766 passed), and Pyright passed on both. I found two cases the tests don't catch yet:

  1. Check the whole schema when a subclass changes a required InitVar. In the override test, the child declares repeat?: number but still extends a base that requires repeat: number. Conversion reports errors=[], yet tsc --strict --noEmit rejects the declaration (TS2430). If the child instead redeclares a required base InitVar with field(init=False) and no default, omitting it from the child declaration leaves it required through the base: TypeScript rejects {"name": "ab"} even though the Python validator accepts it. Please add regressions that check the inherited requirements, not just the child body. If an override can't be represented faithfully, an explicit conversion error is preferable to returning an invalid schema as successful.

  2. Return a diagnostic for an unresolved quoted type. With value: InitVar["MissingType"], python_type_to_typescript_schema on main returns a result with an error. On this head, the resolution call raises NameError instead. Please keep this on the existing result.errors path, identify the field and unresolved name, and add a test that calls the public converter.

Both requests are specific to the new InitVar path; no general dataclass rewrite is needed. Once #549 lands, please rebase and rerun both regression files since the PRs edit the same converter loop.

Reviewed with Copilot assistance.

An InitVar is a constructor argument, so the JSON object has to provide it like any other field.

- Resolve quoted types inside InitVar[...], including local classes and type parameters, and report a name that cannot be resolved as a schema error.
- Leave an inherited InitVar to the base interface, and omit one that field(init=False) takes out of the constructor.
- Report an override that makes a base property optional or removes it, since the derived interface cannot express that.
@vexi1es
S (vexi1es) force-pushed the python-dataclass-initvar branch from 40219dc to c2c803f Compare December 1, 2026 05:15
Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:15

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

InitVar inheritance validation misses incompatible overrides and multiple-base conflicts while incorrectly rejecting valid ClassVar-to-InitVar declarations.

3 open issues

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:26

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 translator incorrectly rejects valid dataclass inheritance when the winning InitVar field is required and another base supplies a default, blocking normal translator construction.

1 open issue
3 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings December 1, 2026 06:07

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

Human review is needed to assess inherited InitVar constructor/schema inconsistencies and quadratic annotation-resolution overhead in dataclass conversion.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@robgruen

robgruen commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Thanks again, S (@vexi1es), for working through these cases. I rechecked bb02ff5: the previously requested examples now pass, and I appreciate the additional regression coverage and the rebase after #549. The earlier fixes do not need to be redone.

The additional checks turned up two more constructor-removal variants of the same inheritance/schema-consistency requirement, plus an avoidable slowdown in the new compatibility checks. These are focused follow-ups within the existing InitVar work, not a request for a general dataclass rewrite.

1. Check inherited constructor exclusions before skipping an unchanged field

For Child(ExcludedInput, RequiredInput), where ExcludedInput declares value: InitVar[int] = field(init=False) and RequiredInput declares value: InitVar[int], the validator accepts {}. However, the generated child interface still extends the required base, so its effective schema requires value, with errors=[].

The unchanged-inherited-field branch bypasses the constructor-removal check in this case. Please check constructor exclusion before leaving the property to the base interfaces.

2. Include ClassVar replacements in the removal check

Similarly, a subclass of RequiredInput that declares value: ClassVar[int] = 3 validates {}, but its emitted interface still inherits a required value. The early ClassVar filtering means this case never reaches the new compatibility checks, and conversion again reports no error.

Please add a focused regression for each removal case, checking the effective inherited requirements against actual validator behavior. If the current interface structure cannot represent a case faithfully, an explicit conversion error is fine, consistent with the earlier request.

3. Reuse resolved base annotations

The base-property helper resolves all of a base's type hints again for each field, including for ordinary dataclasses with no InitVar.

In a synthetic 1,000-field ordinary dataclass subclass, get_type_hints calls increased from 3 on the base revision to 1,003 here. Median node-conversion time over three samples on this machine increased from about 0.021s to 0.572s. Please resolve the base hints once and reuse them rather than repeating full-base resolution per field.

Verification

The 45 focused dataclass tests passed locally on Python 3.14, and Pyright reported zero errors. The two additional removal probes pass on the base revision because unsupported InitVar annotations produce conversion errors; on this head, they fail because the inaccurate schemas are returned with an empty error list. Current CI is also green, including Python 3.11-3.14.

Thanks again for the careful follow-through on these inheritance edge cases.

Reviewed with Copilot assistance.

Copilot AI balanced review requested due to automatic review settings December 2, 2026 09:34

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

Human assessment is needed because inherited InitVar properties with matching requiredness but incompatible types can silently generate invalid TypeScript interfaces without schema errors.

No open issues 🎉

Review effort: Balanced

@vexi1es

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review, pushed a fix for all three, both removal cases now report a conversion error and base hints are resolved once per class, on the 1000 field example I get 3 get_type_hints calls again instead of 1003

Use Omit to preserve constructor-input overrides and conflicting generic bases without duplicating TypeScript assignability rules. Add regression coverage and documentation while retaining requiredness diagnostics and cached base annotations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@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.

Thanks for the fixes!

@robgruen robgruen closed this Dec 2, 2026
@robgruen robgruen reopened this Dec 2, 2026
Copilot AI balanced review requested due to automatic review settings December 2, 2026 18:39

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

A critical diamond-inheritance bug emits an InitVar type that disagrees with Pydantic validation because it uses merged annotations instead of the winning dataclass field.

1 open issue

Review effort: Balanced

Comment on lines +623 to +625
elif isinstance(type_hint, InitVar):
try:
type_hint = _resolve_init_var_type(py_type, attr_name, cast(Any, type_hint).type)
@robgruen
robgruen merged commit 6ac48b9 into microsoft:main Dec 2, 2026
8 checks passed
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