Skip to content
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

[ENG-759] [ENG-1104] patch json.dumps to handle __wrapped__ objects #4166

Merged
merged 6 commits into from
Nov 4, 2024

Conversation

masenf
Copy link
Collaborator

@masenf masenf commented Oct 12, 2024

Unwrap proxied objects if the default serializer doesn't work.

Is this a good idea? That remains to be seen... but it does work.

import json

import reflex as rx


class State(rx.State):
    value: list[int] = [50]

    def foo(self):
        print(json.dumps(self.value))


def index() -> rx.Component:
    return rx.button("Foo", on_click=State.foo)


app = rx.App()
app.add_page(index)

Unwrap proxied objects if the default serializer doesn't work.
Copy link

linear bot commented Oct 12, 2024

@benedikt-bartscher
Copy link
Contributor

Is this a good idea? That remains to be seen... but it does work.

Maybe we should rename it to __reflex_wrapped__ if we decide to patch python internals

@masenf masenf changed the title [ENG-1104] patch json.dumps to handle __wrapped__ objects [ENG-759] [ENG-1104] patch json.dumps to handle __wrapped__ objects Oct 25, 2024
Copy link

linear bot commented Oct 25, 2024

picklelo
picklelo previously approved these changes Oct 29, 2024
`cls` will provide its own default serialization mechanism, passing a `cls`
Encoder class is now also a way to opt-out of our patching shenanigans and just
use your own code.

This will work, provided the library doing the JSON encoding isn't also using
their own custom class.
Many libraries (like httpx, used by openai), will use `from json import dumps`,
and if they do that before `reflex.state` gets imported, then they will get the
original dumps function instead of our patched one.

To workaround this, monkeypatch the `JSONEncoder.default` function instead.

This is also nicer behavior for custom subclasses of JSONEncoder; if someone
wants to opt-out of our monkeypatching, they can simply not call
`super().default(o)` in their subclass, which by default only raises a
TypeError.
@masenf masenf marked this pull request as ready for review October 31, 2024 21:12
@masenf masenf merged commit 163acf7 into main Nov 4, 2024
29 checks passed
@masenf masenf deleted the masenf/json-dumps-patch branch December 12, 2024 07:14
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.

3 participants