Skip to content

fix(python): support default values for array/map field #21707

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2160,13 +2160,8 @@ private String finalizeType(CodegenProperty cp, PythonType pt) {
if (cp.defaultValue == null) {
pt.setDefaultValue("None");
} else {
if (cp.isArray || cp.isMap) {
// TODO handle default value for array/map
pt.setDefaultValue("None");
} else {
//defaultValue = ;
pt.setDefaultValue(cp.defaultValue);
}
//defaultValue = ;
pt.setDefaultValue(cp.defaultValue);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2910,3 +2910,18 @@ components:
- 1.0
- 0.5
- 0.25
ModelWithArrayAndMapDefaults:
type: object
properties:
array:
type: array
items:
type: number
default: [1, 2]
map:
type: object
additionalProperties:
type: string
default:
key1: "value1"
key2: "value2"
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ class DefaultValue(BaseModel):
"""
to test the default value of properties
""" # noqa: E501
array_string_enum_ref_default: Optional[List[StringEnumRef]] = None
array_string_enum_default: Optional[List[StrictStr]] = None
array_string_default: Optional[List[StrictStr]] = None
array_integer_default: Optional[List[StrictInt]] = None
array_string_enum_ref_default: Optional[List[StringEnumRef]] = ["success","failure"]
array_string_enum_default: Optional[List[StrictStr]] = ["success","failure"]
array_string_default: Optional[List[StrictStr]] = ["failure","skipped"]
array_integer_default: Optional[List[StrictInt]] = [1,3]
array_string: Optional[List[StrictStr]] = None
array_string_nullable: Optional[List[StrictStr]] = None
array_string_extension_nullable: Optional[List[StrictStr]] = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Query(BaseModel):
Query
""" # noqa: E501
id: Optional[StrictInt] = Field(default=None, description="Query")
outcomes: Optional[List[StrictStr]] = None
outcomes: Optional[List[StrictStr]] = ["SUCCESS","FAILURE"]
__properties: ClassVar[List[str]] = ["id", "outcomes"]

@field_validator('outcomes')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ class DefaultValue(BaseModel):
"""
to test the default value of properties
""" # noqa: E501
array_string_enum_ref_default: Optional[List[StringEnumRef]] = None
array_string_enum_default: Optional[List[StrictStr]] = None
array_string_default: Optional[List[StrictStr]] = None
array_integer_default: Optional[List[StrictInt]] = None
array_string_enum_ref_default: Optional[List[StringEnumRef]] = ["success","failure"]
array_string_enum_default: Optional[List[StrictStr]] = ["success","failure"]
array_string_default: Optional[List[StrictStr]] = ["failure","skipped"]
array_integer_default: Optional[List[StrictInt]] = [1,3]
array_string: Optional[List[StrictStr]] = None
array_string_nullable: Optional[List[StrictStr]] = None
array_string_extension_nullable: Optional[List[StrictStr]] = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Query(BaseModel):
Query
""" # noqa: E501
id: Optional[StrictInt] = Field(default=None, description="Query")
outcomes: Optional[List[StrictStr]] = None
outcomes: Optional[List[StrictStr]] = ["SUCCESS","FAILURE"]
__properties: ClassVar[List[str]] = ["id", "outcomes"]

@field_validator('outcomes')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ docs/Model200Response.md
docs/ModelApiResponse.md
docs/ModelField.md
docs/ModelReturn.md
docs/ModelWithArrayAndMapDefaults.md
docs/MultiArrays.md
docs/Name.md
docs/NullableClass.md
Expand Down Expand Up @@ -198,6 +199,7 @@ petstore_api/models/model200_response.py
petstore_api/models/model_api_response.py
petstore_api/models/model_field.py
petstore_api/models/model_return.py
petstore_api/models/model_with_array_and_map_defaults.py
petstore_api/models/multi_arrays.py
petstore_api/models/name.py
petstore_api/models/nullable_class.py
Expand Down
1 change: 1 addition & 0 deletions samples/openapi3/client/petstore/python-aiohttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ Class | Method | HTTP request | Description
- [ModelApiResponse](docs/ModelApiResponse.md)
- [ModelField](docs/ModelField.md)
- [ModelReturn](docs/ModelReturn.md)
- [ModelWithArrayAndMapDefaults](docs/ModelWithArrayAndMapDefaults.md)
- [MultiArrays](docs/MultiArrays.md)
- [Name](docs/Name.md)
- [NullableClass](docs/NullableClass.md)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# ModelWithArrayAndMapDefaults


## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**array** | **List[float]** | | [optional] [default to [1,2]]
**map** | **Dict[str, str]** | | [optional]

## Example

```python
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults

# TODO update the JSON string below
json = "{}"
# create an instance of ModelWithArrayAndMapDefaults from a JSON string
model_with_array_and_map_defaults_instance = ModelWithArrayAndMapDefaults.from_json(json)
# print the JSON string representation of the object
print(ModelWithArrayAndMapDefaults.to_json())

# convert the object into a dict
model_with_array_and_map_defaults_dict = model_with_array_and_map_defaults_instance.to_dict()
# create an instance of ModelWithArrayAndMapDefaults from a dict
model_with_array_and_map_defaults_from_dict = ModelWithArrayAndMapDefaults.from_dict(model_with_array_and_map_defaults_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# ModelWithArrayAndMapDefaultsMap


## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**key1** | **str** | | [optional] [default to 'value1']
**key2** | **str** | | [optional] [default to 'value2']

## Example

```python
from petstore_api.models.model_with_array_and_map_defaults_map import ModelWithArrayAndMapDefaultsMap

# TODO update the JSON string below
json = "{}"
# create an instance of ModelWithArrayAndMapDefaultsMap from a JSON string
model_with_array_and_map_defaults_map_instance = ModelWithArrayAndMapDefaultsMap.from_json(json)
# print the JSON string representation of the object
print(ModelWithArrayAndMapDefaultsMap.to_json())

# convert the object into a dict
model_with_array_and_map_defaults_map_dict = model_with_array_and_map_defaults_map_instance.to_dict()
# create an instance of ModelWithArrayAndMapDefaultsMap from a dict
model_with_array_and_map_defaults_map_from_dict = ModelWithArrayAndMapDefaultsMap.from_dict(model_with_array_and_map_defaults_map_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
"ModelApiResponse",
"ModelField",
"ModelReturn",
"ModelWithArrayAndMapDefaults",
"MultiArrays",
"Name",
"NullableClass",
Expand Down Expand Up @@ -233,6 +234,7 @@
from petstore_api.models.model_api_response import ModelApiResponse as ModelApiResponse
from petstore_api.models.model_field import ModelField as ModelField
from petstore_api.models.model_return import ModelReturn as ModelReturn
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults as ModelWithArrayAndMapDefaults
from petstore_api.models.multi_arrays import MultiArrays as MultiArrays
from petstore_api.models.name import Name as Name
from petstore_api.models.nullable_class import NullableClass as NullableClass
Expand Down Expand Up @@ -375,6 +377,7 @@
from petstore_api.models.model_api_response import ModelApiResponse as ModelApiResponse
from petstore_api.models.model_field import ModelField as ModelField
from petstore_api.models.model_return import ModelReturn as ModelReturn
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults as ModelWithArrayAndMapDefaults
from petstore_api.models.multi_arrays import MultiArrays as MultiArrays
from petstore_api.models.name import Name as Name
from petstore_api.models.nullable_class import NullableClass as NullableClass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
from petstore_api.models.model_api_response import ModelApiResponse
from petstore_api.models.model_field import ModelField
from petstore_api.models.model_return import ModelReturn
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults
from petstore_api.models.multi_arrays import MultiArrays
from petstore_api.models.name import Name
from petstore_api.models.nullable_class import NullableClass
Expand Down Expand Up @@ -194,6 +195,7 @@
from petstore_api.models.model_api_response import ModelApiResponse
from petstore_api.models.model_field import ModelField
from petstore_api.models.model_return import ModelReturn
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults
from petstore_api.models.multi_arrays import MultiArrays
from petstore_api.models.name import Name
from petstore_api.models.nullable_class import NullableClass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# coding: utf-8

"""
OpenAPI Petstore

This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\

The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
""" # noqa: E501


from __future__ import annotations
import pprint
import re # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self

class ModelWithArrayAndMapDefaults(BaseModel):
"""
ModelWithArrayAndMapDefaults
""" # noqa: E501
array: Optional[List[float]] = [1,2]
map: Optional[Dict[str, StrictStr]] = None
__properties: ClassVar[List[str]] = ["array", "map"]

model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)


def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))

def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())

@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ModelWithArrayAndMapDefaults from a JSON string"""
return cls.from_dict(json.loads(json_str))

def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.

This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:

* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])

_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict

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

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

_obj = cls.model_validate({
"array": obj.get("array"),
"map": obj.get("map")
})
return _obj


Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# coding: utf-8

"""
OpenAPI Petstore

This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\

The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
""" # noqa: E501


import unittest

from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults

class TestModelWithArrayAndMapDefaults(unittest.TestCase):
"""ModelWithArrayAndMapDefaults unit test stubs"""

def setUp(self):
pass

def tearDown(self):
pass

def make_instance(self, include_optional) -> ModelWithArrayAndMapDefaults:
"""Test ModelWithArrayAndMapDefaults
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `ModelWithArrayAndMapDefaults`
"""
model = ModelWithArrayAndMapDefaults()
if include_optional:
return ModelWithArrayAndMapDefaults(
array = [
1.337
],
map = {
'key' : ''
}
)
else:
return ModelWithArrayAndMapDefaults(
)
"""

def testModelWithArrayAndMapDefaults(self):
"""Test ModelWithArrayAndMapDefaults"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
docs/Model200Response.md
docs/ModelReturn.md
docs/ModelWithArrayAndMapDefaults.md
docs/MultiArrays.md
docs/Name.md
docs/NullableClass.md
Expand Down Expand Up @@ -198,6 +199,7 @@ petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py
petstore_api/models/model200_response.py
petstore_api/models/model_return.py
petstore_api/models/model_with_array_and_map_defaults.py
petstore_api/models/multi_arrays.py
petstore_api/models/name.py
petstore_api/models/nullable_class.py
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ Class | Method | HTTP request | Description
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](docs/Model200Response.md)
- [ModelReturn](docs/ModelReturn.md)
- [ModelWithArrayAndMapDefaults](docs/ModelWithArrayAndMapDefaults.md)
- [MultiArrays](docs/MultiArrays.md)
- [Name](docs/Name.md)
- [NullableClass](docs/NullableClass.md)
Expand Down
Loading
Loading