-
Notifications
You must be signed in to change notification settings - Fork 765
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pydantic v2 inheritance from TypedDict
is flagged as error, even though it's valid Python
#4584
Comments
I couldn't find any example that inherits from Maybe using the |
Hi @alfawal, looks like the Pydantic v2 docs aren't fully up to date yet. In fact, I was myself unaware you could do this, until Samuel Colvin issued a PR on my repo to suggest using |
This is confusing enough to me that I've started a discussion in the Pydantic repo on this! I'll update this issue with what they say, in due course. |
@alfawal I think it's worth closing this issue, as it's something that type checkers are unlikely to want to support (it's too specific to Pydantic and it violates PEP 589, so Pylance and Pyright are behaving as expected). For any future readers, see the workaround in the Pydantic repo discussion for more details. The code snippet given above works perfectly fine at runtime and the Pylance errors can be turned off in VS code by simply adding a from pydantic import TypeAdapter, field_validator
from typing_extensions import TypedDict
class Item(TypedDict):
id: int
price: float
description: str | None
@field_validator("price", mode="before")
def check_non_zero(cls, v):
# type: ignore
if v <= 0:
raise ValueError("price cannot be zero")
else:
return v Maybe at some point in the future we might see this not be a type issue! But for now things work as intended. |
2023.7.10
Code Snippet
Repro steps
Expected behavior
There shouldn't be any errors shown by Pylance when writing this code in VS Code. If the above code snippet is run, it produces the exact correct behavior (it's perfectly valid Python, there are no syntax errors, and the code works as intended).
Background:
Pydantic has added support for directly inheriting from Python's
TypedDict
instead of inheriting from its ownBaseModel
. UsingTypedDict
is very useful for performance when we need to just validate dicts, avoiding unnecessary serialization/deserialization performance overheads in Python.Because Pydantic natively allows inheritance from
TypedDict
, it also allows defining methods in the resulting Pydantic object used downstream, such as the one shown in thefield_validator
example in the snippet above.Actual behavior
Pylance highlights all code under the defined method as an error, even though it isn't an error from a Python perspective. The following error is produced:
Logs
The text was updated successfully, but these errors were encountered: