-
-
Notifications
You must be signed in to change notification settings - Fork 36
Add GenericEncoder and Pydantic support #63
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
base: main
Are you sure you want to change the base?
Conversation
Additional updates:
Other notes:
|
|
||
def _is_pydantic_model_type(typ: Type) -> bool: | ||
return any( | ||
base.__module__.startswith("pydantic") and base.__name__ == "BaseModel" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pydantic also has a GenericModel
do we need to consider that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right—Pydantic does have GenericModel
, but that's only part of Pydantic v1. Fortunately, GenericModel
also inherits from BaseModel
, so any logic that targets BaseModel
will still work seamlessly for GenericModel
instances too.
On a related note, I wanted to raise a question about the is_allowed_type
check. In my experience, this utility has become a bottleneck for extending zero with support for new types. While the encoder side is quite flexible and easy to extend, is_allowed_type
feels a bit restrictive—it requires explicitly adding each new supported type, which slows down development.
I'd suggest either removing this check altogether or generalizing it—for example, by checking isinstance(obj, type)
—so it can handle any class-based types, including dataclasses, msgspec, and Pydantic models, without special casing.
Curious to hear your thoughts on this!
|
||
class GenericEncoder(MsgspecEncoder): | ||
def encode(self, data: Any) -> bytes: | ||
if PYDANTIC_AVAILABLE and isinstance(data, BaseModel): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same question here
Nice and neat work! 🙌 |
This PR introduces built-in Pydantic support via a new
GenericEncoder
that is compatible with both Pydantic V1 and V2.Key changes:
GenericEncoder
is now the default encoder.