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

[REQ][Python] Remove Optional[] from from_dict/from_json method in models #20796

Open
unarist opened this issue Mar 4, 2025 · 0 comments
Open

Comments

@unarist
Copy link

unarist commented Mar 4, 2025

Is your feature request related to a problem? Please describe.

This generated from_dict method returns None only if None is passed as obj.

@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Pet from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"name": obj.get("name"),
"category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None,
"photoUrls": obj.get("photoUrls"),
"tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None,
"status": obj.get("status")
})
return _obj

So I need to check its return value every time even if I actually passing non-None value...

pet = Pet.from_dict(pet_dict)
assert(pet is not None)

# or

if pet is None:
  raise Exception("should not be reached here")

Describe the solution you'd like

Remove Optional[] from the obj parameter and the return value.

 def from_dict(cls, obj: Dict[str, Any]) -> Self: 
     """Create an instance of Pet from a dict""" 
     if not isinstance(obj, dict): 
         return cls.model_validate(obj) 

    ...

Describe alternatives you've considered

@overload also provides better typing:

    @overload
    def from_dict(cls, obj: None) -> None:
        ...

    @overload
    def from_dict(cls, obj: Dict[str, Any]) -> Self:
        ...

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of Pet from a dict"""
        if obj is None:
            return None

        ...

but I don't think this method should accept None value. I'm agree with checking None in caller side, like the commit which introduce None checking does.

Additional context

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

1 participant