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

Optional Field args don't work as expected #278

Open
mure opened this issue Sep 30, 2022 · 2 comments
Open

Optional Field args don't work as expected #278

mure opened this issue Sep 30, 2022 · 2 comments

Comments

@mure
Copy link

mure commented Sep 30, 2022

Describe the bug
When using the Field annotation on an arg to be converted into a JSON field, nullable types don't work as expected. Using Optional directly throws an error, but you can work around this by using the x | None syntax instead. However, this is causing the request body to include unintended nulls.

To Reproduce

@json
@args(Field("a"))
@patch("route")
def patch(self, a: Optional[str] = None):
   pass

Result:
TypeError: issubclass() arg 1 must be a class

@json
@args(Field("a"))
@patch("route")
def patch(self, a: str | None = None):
   pass

client.patch()

Result

{ "a": null }

It would be nice if this had the same behavior as Query params.

@mateochr
Copy link

mateochr commented Aug 7, 2024

Hi @mure found any workaround for this?

@mateochr
Copy link

mateochr commented Aug 8, 2024

I have created this class that takes the idea from the Query function annotation.

from uplink import Field


class CustomField(Field):
    def __init__(self, name=None, type=None, encode_none=None):
        super(CustomField, self).__init__(name, type)
        self._encode_none = encode_none

    def _modify_request(self, request_builder, value):
        if value is None:
            if self._encode_none is None:
                return
            value = self._encode_none

        super(CustomField, self)._modify_request(request_builder, value)

But still i don't like this approach, what if you want to pass something in the body that has None value?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants