OpenAPITools / OpenAPITools/openapi-generator

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

Open
#20,796 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Enhancement: Feature
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

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

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

https://github.com/OpenAPITools/openapi-generator/blob/c96d3088c506f6af09b095e7b25828fce17985dc/samples/client/echo_api/python/openapi_client/models/pet.py#L101-L118

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with samples/client/echo_api/python/openapi_client/models/pet.py, especially the from_dict and from_json entry points linked in the issue, and inspect how their annotations and None handling are generated. Locate the generator source responsible and check any existing Python model tests. Done means generated methods require non-None dictionaries and return the model type without Optional annotations, with callers handling None before invocation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
api, tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.