Skip to content

Commit

Permalink
python: type generated client using Self (#16693)
Browse files Browse the repository at this point in the history
* python: type generated client using Self

This doesn't offer a clear win but this helps for:

* Using modern types and making the typing intent clearer
* Decreasing the need for `from __future__ import annotations`, since a
  class can now refer to itself without using its name
* Using more `cls` to automatically refer to the class, instead of
  respecifying the class name every time

Self is available from Python 3.11 and is provided in typing_extensions
(since 4.0.0) as a fallback for older versions

See: https://peps.python.org/pep-0673/
See: https://github.com/python/typing_extensions/blob/main/CHANGELOG.md#added-in-version-400

* generate code
  • Loading branch information
multani authored Oct 1, 2023
1 parent bd1caf6 commit cec5b89
Show file tree
Hide file tree
Showing 195 changed files with 1,723 additions and 824 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import re # noqa: F401
from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict
from typing_extensions import Literal
from pydantic import StrictStr, Field
try:
from typing import Self
except ImportError:
from typing_extensions import Self

{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}]

Expand Down Expand Up @@ -97,13 +101,13 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return v

@classmethod
def from_dict(cls, obj: dict) -> {{{classname}}}:
def from_dict(cls, obj: dict) -> Self:
return cls.from_json(json.dumps(obj))

@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
def from_json(cls, json_str: str) -> Self:
"""Returns the object represented by the json string"""
instance = {{{classname}}}.model_construct()
instance = cls.model_construct()
{{#isNullable}}
if json_str is None:
return instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ from enum import Enum
{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}}
{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}}
{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}}
try:
from typing import Self
except ImportError:
from typing_extensions import Self


class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum):
Expand All @@ -22,9 +26,9 @@ class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum):
{{/enumVars}}

@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
def from_json(cls, json_str: str) -> Self:
"""Create an instance of {{classname}} from a JSON string"""
return {{classname}}(json.loads(json_str))
return cls(json.loads(json_str))

{{#defaultValue}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import json
{{#vendorExtensions.x-py-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-model-imports}}
from typing import Dict, Any
try:
from typing import Self
except ImportError:
from typing_extensions import Self

class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}):
"""
Expand Down Expand Up @@ -113,7 +118,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return json.dumps(self.to_dict())

@classmethod
def from_json(cls, json_str: str) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}:
def from_json(cls, json_str: str) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}:
"""Create an instance of {{{classname}}} from a JSON string"""
return cls.from_dict(json.loads(json_str))

Expand Down Expand Up @@ -215,7 +220,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return _dict

@classmethod
def from_dict(cls, obj: dict) -> {{^hasChildren}}{{{classname}}}{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union({{#children}}{{{classname}}}{{^-last}}, {{/-last}}{{/children}}){{/discriminator}}{{^discriminator}}{{{classname}}}{{/discriminator}}{{/hasChildren}}:
def from_dict(cls, obj: dict) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}:
"""Create an instance of {{{classname}}} from a dict"""
{{#hasChildren}}
{{#discriminator}}
Expand All @@ -235,7 +240,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return None

if not isinstance(obj, dict):
return {{{classname}}}.model_validate(obj)
return cls.model_validate(obj)

{{#disallowAdditionalPropertiesIfNotPresent}}
{{^isAdditionalPropertiesTrue}}
Expand All @@ -246,7 +251,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}

{{/isAdditionalPropertiesTrue}}
{{/disallowAdditionalPropertiesIfNotPresent}}
_obj = {{{classname}}}.model_validate({
_obj = cls.model_validate({
{{#allVars}}
{{#isContainer}}
{{#isArray}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import re # noqa: F401
from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict
from typing_extensions import Literal
from pydantic import StrictStr, Field
try:
from typing import Self
except ImportError:
from typing_extensions import Self

{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}]

Expand Down Expand Up @@ -97,13 +101,13 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return v

@classmethod
def from_dict(cls, obj: dict) -> {{{classname}}}:
def from_dict(cls, obj: dict) -> Self:
return cls.from_json(json.dumps(obj))

@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
def from_json(cls, json_str: str) -> Self:
"""Returns the object represented by the json string"""
instance = {{{classname}}}.model_construct()
instance = cls.model_construct()
{{#isNullable}}
if json_str is None:
return instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import warnings

from pydantic import validate_call, ValidationError
from typing import Dict, List, Optional, Tuple


from openapi_client.api_client import ApiClient
Expand Down Expand Up @@ -130,28 +131,28 @@ def test_auth_http_basic_with_http_info(self, **kwargs) -> ApiResponse: # noqa:
_params[_key] = _val
del _params['kwargs']

_collection_formats = {}
_collection_formats: Dict[str, str] = {}

# process the path parameters
_path_params = {}
_path_params: Dict[str, str] = {}

# process the query parameters
_query_params = []
_query_params: List[Tuple[str, str]] = []
# process the header parameters
_header_params = dict(_params.get('_headers', {}))
# process the form parameters
_form_params = []
_files = {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, str] = {}
# process the body parameter
_body_params = None
# set the HTTP header `Accept`
_header_params['Accept'] = self.api_client.select_header_accept(
['text/plain']) # noqa: E501

# authentication setting
_auth_settings = ['http_auth'] # noqa: E501
_auth_settings: List[str] = ['http_auth'] # noqa: E501

_response_types_map = {
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
}

Expand Down
Loading

0 comments on commit cec5b89

Please sign in to comment.