Skip to content

Commit b47c2b8

Browse files
committed
fix(python): support default values for array/map field
1 parent f659457 commit b47c2b8

21 files changed

+924
-7
lines changed

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2160,13 +2160,8 @@ private String finalizeType(CodegenProperty cp, PythonType pt) {
21602160
if (cp.defaultValue == null) {
21612161
pt.setDefaultValue("None");
21622162
} else {
2163-
if (cp.isArray || cp.isMap) {
2164-
// TODO handle default value for array/map
2165-
pt.setDefaultValue("None");
2166-
} else {
2167-
//defaultValue = ;
2168-
pt.setDefaultValue(cp.defaultValue);
2169-
}
2163+
//defaultValue = ;
2164+
pt.setDefaultValue(cp.defaultValue);
21702165
}
21712166
}
21722167

modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2910,3 +2910,20 @@ components:
29102910
- 1.0
29112911
- 0.5
29122912
- 0.25
2913+
ModelWithArrayAndMapDefaults:
2914+
type: object
2915+
properties:
2916+
array:
2917+
type: array
2918+
items:
2919+
type: number
2920+
default: [1, 2]
2921+
map:
2922+
type: object
2923+
properties:
2924+
key1:
2925+
type: string
2926+
default: "value1"
2927+
key2:
2928+
type: string
2929+
default: "value2"
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# ModelWithArrayAndMapDefaults
2+
3+
4+
## Properties
5+
6+
Name | Type | Description | Notes
7+
------------ | ------------- | ------------- | -------------
8+
**array** | **List[float]** | | [optional] [default to [1,2]]
9+
**map** | **Dict[str, str]** | | [optional]
10+
11+
## Example
12+
13+
```python
14+
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults
15+
16+
# TODO update the JSON string below
17+
json = "{}"
18+
# create an instance of ModelWithArrayAndMapDefaults from a JSON string
19+
model_with_array_and_map_defaults_instance = ModelWithArrayAndMapDefaults.from_json(json)
20+
# print the JSON string representation of the object
21+
print(ModelWithArrayAndMapDefaults.to_json())
22+
23+
# convert the object into a dict
24+
model_with_array_and_map_defaults_dict = model_with_array_and_map_defaults_instance.to_dict()
25+
# create an instance of ModelWithArrayAndMapDefaults from a dict
26+
model_with_array_and_map_defaults_from_dict = ModelWithArrayAndMapDefaults.from_dict(model_with_array_and_map_defaults_dict)
27+
```
28+
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
29+
30+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
6+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
7+
8+
The version of the OpenAPI document: 1.0.0
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
15+
from __future__ import annotations
16+
import pprint
17+
import re # noqa: F401
18+
import json
19+
20+
from pydantic import BaseModel, ConfigDict, StrictStr
21+
from typing import Any, ClassVar, Dict, List, Optional
22+
from typing import Optional, Set
23+
from typing_extensions import Self
24+
25+
class ModelWithArrayAndMapDefaults(BaseModel):
26+
"""
27+
ModelWithArrayAndMapDefaults
28+
""" # noqa: E501
29+
array: Optional[List[float]] = [1,2]
30+
map: Optional[Dict[str, StrictStr]] = None
31+
__properties: ClassVar[List[str]] = ["array", "map"]
32+
33+
model_config = ConfigDict(
34+
populate_by_name=True,
35+
validate_assignment=True,
36+
protected_namespaces=(),
37+
)
38+
39+
40+
def to_str(self) -> str:
41+
"""Returns the string representation of the model using alias"""
42+
return pprint.pformat(self.model_dump(by_alias=True))
43+
44+
def to_json(self) -> str:
45+
"""Returns the JSON representation of the model using alias"""
46+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
47+
return json.dumps(self.to_dict())
48+
49+
@classmethod
50+
def from_json(cls, json_str: str) -> Optional[Self]:
51+
"""Create an instance of ModelWithArrayAndMapDefaults from a JSON string"""
52+
return cls.from_dict(json.loads(json_str))
53+
54+
def to_dict(self) -> Dict[str, Any]:
55+
"""Return the dictionary representation of the model using alias.
56+
57+
This has the following differences from calling pydantic's
58+
`self.model_dump(by_alias=True)`:
59+
60+
* `None` is only added to the output dict for nullable fields that
61+
were set at model initialization. Other fields with value `None`
62+
are ignored.
63+
"""
64+
excluded_fields: Set[str] = set([
65+
])
66+
67+
_dict = self.model_dump(
68+
by_alias=True,
69+
exclude=excluded_fields,
70+
exclude_none=True,
71+
)
72+
return _dict
73+
74+
@classmethod
75+
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
76+
"""Create an instance of ModelWithArrayAndMapDefaults from a dict"""
77+
if obj is None:
78+
return None
79+
80+
if not isinstance(obj, dict):
81+
return cls.model_validate(obj)
82+
83+
_obj = cls.model_validate({
84+
"array": obj.get("array"),
85+
"map": obj.get("map")
86+
})
87+
return _obj
88+
89+
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
6+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
7+
8+
The version of the OpenAPI document: 1.0.0
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
15+
import unittest
16+
17+
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults
18+
19+
class TestModelWithArrayAndMapDefaults(unittest.TestCase):
20+
"""ModelWithArrayAndMapDefaults unit test stubs"""
21+
22+
def setUp(self):
23+
pass
24+
25+
def tearDown(self):
26+
pass
27+
28+
def make_instance(self, include_optional) -> ModelWithArrayAndMapDefaults:
29+
"""Test ModelWithArrayAndMapDefaults
30+
include_optional is a boolean, when False only required
31+
params are included, when True both required and
32+
optional params are included """
33+
# uncomment below to create an instance of `ModelWithArrayAndMapDefaults`
34+
"""
35+
model = ModelWithArrayAndMapDefaults()
36+
if include_optional:
37+
return ModelWithArrayAndMapDefaults(
38+
array = [
39+
1.337
40+
],
41+
map = {
42+
'key' : ''
43+
}
44+
)
45+
else:
46+
return ModelWithArrayAndMapDefaults(
47+
)
48+
"""
49+
50+
def testModelWithArrayAndMapDefaults(self):
51+
"""Test ModelWithArrayAndMapDefaults"""
52+
# inst_req_only = self.make_instance(include_optional=False)
53+
# inst_req_and_optional = self.make_instance(include_optional=True)
54+
55+
if __name__ == '__main__':
56+
unittest.main()
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# ModelWithArrayAndMapDefaults
2+
3+
4+
## Properties
5+
Name | Type | Description | Notes
6+
------------ | ------------- | ------------- | -------------
7+
**array** | **List[float]** | | [optional] [default to [1,2]]
8+
**map** | **Dict[str, str]** | | [optional]
9+
10+
## Example
11+
12+
```python
13+
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults
14+
15+
# TODO update the JSON string below
16+
json = "{}"
17+
# create an instance of ModelWithArrayAndMapDefaults from a JSON string
18+
model_with_array_and_map_defaults_instance = ModelWithArrayAndMapDefaults.from_json(json)
19+
# print the JSON string representation of the object
20+
print ModelWithArrayAndMapDefaults.to_json()
21+
22+
# convert the object into a dict
23+
model_with_array_and_map_defaults_dict = model_with_array_and_map_defaults_instance.to_dict()
24+
# create an instance of ModelWithArrayAndMapDefaults from a dict
25+
model_with_array_and_map_defaults_from_dict = ModelWithArrayAndMapDefaults.from_dict(model_with_array_and_map_defaults_dict)
26+
```
27+
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
28+
29+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
6+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
7+
8+
The version of the OpenAPI document: 1.0.0
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
15+
from __future__ import annotations
16+
import pprint
17+
import re # noqa: F401
18+
import json
19+
20+
21+
from typing import Dict, List, Optional
22+
from pydantic import BaseModel, StrictStr, conlist
23+
24+
class ModelWithArrayAndMapDefaults(BaseModel):
25+
"""
26+
ModelWithArrayAndMapDefaults
27+
"""
28+
array: Optional[conlist(float)] = None
29+
map: Optional[Dict[str, StrictStr]] = None
30+
__properties = ["array", "map"]
31+
32+
class Config:
33+
"""Pydantic configuration"""
34+
allow_population_by_field_name = True
35+
validate_assignment = True
36+
37+
def to_str(self) -> str:
38+
"""Returns the string representation of the model using alias"""
39+
return pprint.pformat(self.dict(by_alias=True))
40+
41+
def to_json(self) -> str:
42+
"""Returns the JSON representation of the model using alias"""
43+
return json.dumps(self.to_dict())
44+
45+
@classmethod
46+
def from_json(cls, json_str: str) -> ModelWithArrayAndMapDefaults:
47+
"""Create an instance of ModelWithArrayAndMapDefaults from a JSON string"""
48+
return cls.from_dict(json.loads(json_str))
49+
50+
def to_dict(self):
51+
"""Returns the dictionary representation of the model using alias"""
52+
_dict = self.dict(by_alias=True,
53+
exclude={
54+
},
55+
exclude_none=True)
56+
return _dict
57+
58+
@classmethod
59+
def from_dict(cls, obj: dict) -> ModelWithArrayAndMapDefaults:
60+
"""Create an instance of ModelWithArrayAndMapDefaults from a dict"""
61+
if obj is None:
62+
return None
63+
64+
if not isinstance(obj, dict):
65+
return ModelWithArrayAndMapDefaults.parse_obj(obj)
66+
67+
_obj = ModelWithArrayAndMapDefaults.parse_obj({
68+
"array": obj.get("array"),
69+
"map": obj.get("map")
70+
})
71+
return _obj
72+
73+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
6+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
7+
8+
The version of the OpenAPI document: 1.0.0
9+
Generated by OpenAPI Generator (https://openapi-generator.tech)
10+
11+
Do not edit the class manually.
12+
""" # noqa: E501
13+
14+
15+
import unittest
16+
import datetime
17+
18+
from petstore_api.models.model_with_array_and_map_defaults import ModelWithArrayAndMapDefaults # noqa: E501
19+
20+
class TestModelWithArrayAndMapDefaults(unittest.TestCase):
21+
"""ModelWithArrayAndMapDefaults unit test stubs"""
22+
23+
def setUp(self):
24+
pass
25+
26+
def tearDown(self):
27+
pass
28+
29+
def make_instance(self, include_optional) -> ModelWithArrayAndMapDefaults:
30+
"""Test ModelWithArrayAndMapDefaults
31+
include_option is a boolean, when False only required
32+
params are included, when True both required and
33+
optional params are included """
34+
# uncomment below to create an instance of `ModelWithArrayAndMapDefaults`
35+
"""
36+
model = ModelWithArrayAndMapDefaults() # noqa: E501
37+
if include_optional:
38+
return ModelWithArrayAndMapDefaults(
39+
array = [
40+
1.337
41+
],
42+
map = {
43+
'key' : ''
44+
}
45+
)
46+
else:
47+
return ModelWithArrayAndMapDefaults(
48+
)
49+
"""
50+
51+
def testModelWithArrayAndMapDefaults(self):
52+
"""Test ModelWithArrayAndMapDefaults"""
53+
# inst_req_only = self.make_instance(include_optional=False)
54+
# inst_req_and_optional = self.make_instance(include_optional=True)
55+
56+
if __name__ == '__main__':
57+
unittest.main()

0 commit comments

Comments
 (0)