Skip to content

implement dunder method __msgspec_encode__ as a last resort encoding method - #1311

Open
Vizonex wants to merge 2 commits into
msgspec:mainfrom
Vizonex:dunder-encoder-decoder-methods
Open

Vizonex wants to merge 2 commits into
msgspec:mainfrom
Vizonex:dunder-encoder-decoder-methods

Conversation

@Vizonex

@Vizonex Vizonex commented Oct 24, 2026

Copy link
Copy Markdown

I'm adding in an implementation for encoding and decoding objects at the class level as a last resort this is so that famous libraries like yarl can be supported but it hands over that responsibility to yarl to configure unless a hook is provided already. This will also allow other users to do the same with their own libraries allowing msgspec to remain in competition with pydantic which supports yarl already.

I'm also looking at __msgspec_decode__ but I have no idea where to inject it's code yet so It's still ongoing work. But feel free to review my current code for improvement or places to inject __msgspec_decode__ (should be a @classmethod wrapper) for decoding support as last resort. I'll be adding these hooks to yarl.URL if this PR is accepted as I am apart of aio-libs's triage and having supported pydantic already and users wanting to try yarl with msgspec without going through the process of needing to add a callback hook seems to be the laziest approach that should be welcomed by many.

Fixes #707 but with a different approach.

To demonstrate the approch I'm using a different class name to show how exactly I plan for this newly added feature to work, I have not figured out built-ins yet but json and msgspack (encoding only) are supported now.

from yarl import URL

from msgspec import Struct
from msgspec.json import encode


class CustomURL:
    def __init__(self, url: str):
        self._url = URL(url)

    # I have this part figured out already.
    def __msgspec_encode__(self):
        return self._url.human_repr()

    # This part has not been implemented btw because
    # I can't figure out where to inject it yet - Vizonex
    @classmethod
    def __msgspec_decode__(cls, data: str):
        return cls(data)

class Proxy(Struct):
    url: CustomURL


proxy = Proxy(CustomURL("socks4://127.0.0.1:2763"))

data = encode(proxy)
print(data)

This branch has not been deployed

No deployments
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.

Accept hook functions in Meta for more ergonomic support of custom data types

1 participant