You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Include dataclass InitVar fields in Python prompt schemas - #547
A dataclass that uses InitVar cannot be used with TypeChatJsonTranslator, and its prompt schema describes the field as any.
fromdataclassesimportInitVar, dataclassfromtypechatimportTypeChatValidator, python_type_to_typescript_schema@dataclassclassRepeated:
name: strrepeat: InitVar[int]
def__post_init__(self, repeat: int) ->None:
self.name=self.name*repeatresult=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 requiredprint(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
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.
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.
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
Resolve quoted InitVar types in generic dataclasses
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.
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.
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
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
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.
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:
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.
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.
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.
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.
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.
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.
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.
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>
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A dataclass that uses
InitVarcannot be used withTypeChatJsonTranslator, and its prompt schema describes the field asany.The validator already treats
repeatas a required integer, because it is a constructor argument. The schema conversion did not recogniseInitVar, so it reported an error and fell back toany; with the default_raise_on_schema_errors, constructing aTypeChatJsonTranslatorfor the class raises.Change
When walking dataclass fields,
InitVar[T]is unwrapped toT(a bareInitVarbecomesany) before the property is declared, so the field is emitted with its real type, optionality and comment. This follows theClassVarhandling added in #533: the emitted properties again match what the validator accepts.Following review, the
InitVarpath also:InitVar[...], including a class defined inside a function and the type parameters of a generic class; a name that cannot be resolved is reported inresult.errorswith the field and the name;InitVarthat 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;InitVarthatfield(init=False)takes out of the constructor when it has no default;ClassVar), because the derived interface cannot express that; all bases are checked, and a required inheritedInitVaris declared on the subclass when another base has it as optional;get_type_hintscalls.Tests
python/tests/test_dataclass_initvars.pycovers required, defaulted,Annotated, inherited, bare, quoted, local and genericInitVars, theinit=Falsecases, 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
mainafter #549. Ran frompython/on Windows:pytest: 856 passed, 3 skipped on Python 3.11; 859 passed on Python 3.14npx pyright: 0 errors