Apply strict=True to __init__ in mypy plugin#9998
Apply strict=True to __init__ in mypy plugin#9998sydney-runkle merged 3 commits intopydantic:mainfrom
strict=True to __init__ in mypy plugin#9998Conversation
CodSpeed Performance ReportMerging #9998 will not alter performanceComparing Summary
|
dmontagu
left a comment
There was a problem hiding this comment.
This looks great, the only concern I have, as noted in the issue #9997, is whether we might under some circumstances emit type errors for valid (and non-pathological) strict mode usage where it does not currently emit type errors. If that's the case, I'd feel better making this opt-in via a new plugin strictness setting.
The important question is — are there any patterns of usage where you might realistically have a strict-mode model (or field) where it is convenient to not get type errors for passing in values that are not validated.
I'll note that since @dataclass_transform will give errors any time you provide a non-valid value, anyone not using the mypy plugin will probably always get type errors for providing invalid values (whether in strict mode or not); I would consider that a fairly strong argument for moving the mypy plugin in a stricter-typed __init__ direction — for the sake of improved consistency with the rest of the python ecosystem.
I'll see what @sydney-runkle thinks, but I think I'm good merging this unless there's some obvious/common/problematic scenario that this introduces issues for. I can't think of one, and for what it's worth I'd also be okay merging and rolling this back if such issues get reported (and reworking to require opting into this behavior via some config setting).
Agreed, happy to merge this as is for now. I think it's fair to say that our |
Change Summary
I've added a feature to
pydantic-mypywhere type annotations for__init__will apply to fields withstrict=True, even wheninit_typedset toFalse. Additionally, ifmodel_config['strict'] = Trueis set for a model, then all fields will be typed in__init__unless overridden withField(strict=True).Currently, this feature only works with
a: int = Field(strict=True)and not witha: Annotated[int, Field(strict=True)]ora: Annotated[int, Strict(strict=True)]. It is also implemented only for__init__and not forvalidate_callor other methods.Example Code
Related issue number
fix #9997
Checklist