Skip to content

Commit 91435aa

Browse files
committed
Update samples and docs with oneOf enum normalization
1 parent de90b6b commit 91435aa

File tree

12 files changed

+84
-536
lines changed

12 files changed

+84
-536
lines changed

samples/openapi3/client/petstore/python-aiohttp/docs/OneOfEnumString.md

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,16 @@
22

33
oneOf enum strings
44

5-
## Properties
5+
## Enum
66

7-
Name | Type | Description | Notes
8-
------------ | ------------- | ------------- | -------------
7+
* `A` (value: `'a'`)
98

10-
## Example
9+
* `B` (value: `'b'`)
1110

12-
```python
13-
from petstore_api.models.one_of_enum_string import OneOfEnumString
11+
* `C` (value: `'c'`)
1412

15-
# TODO update the JSON string below
16-
json = "{}"
17-
# create an instance of OneOfEnumString from a JSON string
18-
one_of_enum_string_instance = OneOfEnumString.from_json(json)
19-
# print the JSON string representation of the object
20-
print(OneOfEnumString.to_json())
13+
* `D` (value: `'d'`)
2114

22-
# convert the object into a dict
23-
one_of_enum_string_dict = one_of_enum_string_instance.to_dict()
24-
# create an instance of OneOfEnumString from a dict
25-
one_of_enum_string_from_dict = OneOfEnumString.from_dict(one_of_enum_string_dict)
26-
```
2715
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
2816

2917

samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_enum_string.py

Lines changed: 12 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -14,124 +14,26 @@
1414

1515
from __future__ import annotations
1616
import json
17-
import pprint
18-
from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator
19-
from typing import Any, List, Optional
20-
from petstore_api.models.enum_string1 import EnumString1
21-
from petstore_api.models.enum_string2 import EnumString2
22-
from pydantic import StrictStr, Field
23-
from typing import Union, List, Set, Optional, Dict
24-
from typing_extensions import Literal, Self
17+
from enum import Enum
18+
from typing_extensions import Self
2519

26-
ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"]
2720

28-
class OneOfEnumString(BaseModel):
21+
class OneOfEnumString(str, Enum):
2922
"""
3023
oneOf enum strings
3124
"""
32-
# data type: EnumString1
33-
oneof_schema_1_validator: Optional[EnumString1] = None
34-
# data type: EnumString2
35-
oneof_schema_2_validator: Optional[EnumString2] = None
36-
actual_instance: Optional[Union[EnumString1, EnumString2]] = None
37-
one_of_schemas: Set[str] = { "EnumString1", "EnumString2" }
3825

39-
model_config = ConfigDict(
40-
validate_assignment=True,
41-
protected_namespaces=(),
42-
)
43-
44-
45-
def __init__(self, *args, **kwargs) -> None:
46-
if args:
47-
if len(args) > 1:
48-
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
49-
if kwargs:
50-
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
51-
super().__init__(actual_instance=args[0])
52-
else:
53-
super().__init__(**kwargs)
54-
55-
@field_validator('actual_instance')
56-
def actual_instance_must_validate_oneof(cls, v):
57-
instance = OneOfEnumString.model_construct()
58-
error_messages = []
59-
match = 0
60-
# validate data type: EnumString1
61-
if not isinstance(v, EnumString1):
62-
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`")
63-
else:
64-
match += 1
65-
# validate data type: EnumString2
66-
if not isinstance(v, EnumString2):
67-
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`")
68-
else:
69-
match += 1
70-
if match > 1:
71-
# more than 1 match
72-
raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
73-
elif match == 0:
74-
# no match
75-
raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
76-
else:
77-
return v
78-
79-
@classmethod
80-
def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self:
81-
return cls.from_json(json.dumps(obj))
26+
"""
27+
allowed enum values
28+
"""
29+
A = 'a'
30+
B = 'b'
31+
C = 'c'
32+
D = 'd'
8233

8334
@classmethod
8435
def from_json(cls, json_str: str) -> Self:
85-
"""Returns the object represented by the json string"""
86-
instance = cls.model_construct()
87-
error_messages = []
88-
match = 0
89-
90-
# deserialize data into EnumString1
91-
try:
92-
instance.actual_instance = EnumString1.from_json(json_str)
93-
match += 1
94-
except (ValidationError, ValueError) as e:
95-
error_messages.append(str(e))
96-
# deserialize data into EnumString2
97-
try:
98-
instance.actual_instance = EnumString2.from_json(json_str)
99-
match += 1
100-
except (ValidationError, ValueError) as e:
101-
error_messages.append(str(e))
102-
103-
if match > 1:
104-
# more than 1 match
105-
raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
106-
elif match == 0:
107-
# no match
108-
raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
109-
else:
110-
return instance
111-
112-
def to_json(self) -> str:
113-
"""Returns the JSON representation of the actual instance"""
114-
if self.actual_instance is None:
115-
return "null"
116-
117-
if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
118-
return self.actual_instance.to_json()
119-
else:
120-
return json.dumps(self.actual_instance)
121-
122-
def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]:
123-
"""Returns the dict representation of the actual instance"""
124-
if self.actual_instance is None:
125-
return None
126-
127-
if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
128-
return self.actual_instance.to_dict()
129-
else:
130-
# primitive type
131-
return self.actual_instance
132-
133-
def to_str(self) -> str:
134-
"""Returns the string representation of the actual instance"""
135-
return pprint.pformat(self.model_dump())
36+
"""Create an instance of OneOfEnumString from a JSON string"""
37+
return cls(json.loads(json_str))
13638

13739

samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,6 @@ def to_dict(self) -> Dict[str, Any]:
7575
# override the default output from pydantic by calling `to_dict()` of nested_pig
7676
if self.nested_pig:
7777
_dict['nested_pig'] = self.nested_pig.to_dict()
78-
# override the default output from pydantic by calling `to_dict()` of nested_oneof_enum_string
79-
if self.nested_oneof_enum_string:
80-
_dict['nested_oneof_enum_string'] = self.nested_oneof_enum_string.to_dict()
8178
return _dict
8279

8380
@classmethod
@@ -92,7 +89,7 @@ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
9289
_obj = cls.model_validate({
9390
"size": obj.get("size"),
9491
"nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None,
95-
"nested_oneof_enum_string": OneOfEnumString.from_dict(obj["nested_oneof_enum_string"]) if obj.get("nested_oneof_enum_string") is not None else None
92+
"nested_oneof_enum_string": obj.get("nested_oneof_enum_string")
9693
})
9794
return _obj
9895

samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/OneOfEnumString.md

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,16 @@
22

33
oneOf enum strings
44

5-
## Properties
6-
Name | Type | Description | Notes
7-
------------ | ------------- | ------------- | -------------
8-
9-
## Example
10-
11-
```python
12-
from petstore_api.models.one_of_enum_string import OneOfEnumString
13-
14-
# TODO update the JSON string below
15-
json = "{}"
16-
# create an instance of OneOfEnumString from a JSON string
17-
one_of_enum_string_instance = OneOfEnumString.from_json(json)
18-
# print the JSON string representation of the object
19-
print OneOfEnumString.to_json()
20-
21-
# convert the object into a dict
22-
one_of_enum_string_dict = one_of_enum_string_instance.to_dict()
23-
# create an instance of OneOfEnumString from a dict
24-
one_of_enum_string_from_dict = OneOfEnumString.from_dict(one_of_enum_string_dict)
25-
```
5+
## Enum
6+
7+
* `A` (value: `'a'`)
8+
9+
* `B` (value: `'b'`)
10+
11+
* `C` (value: `'c'`)
12+
13+
* `D` (value: `'d'`)
14+
2615
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
2716

2817

samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/one_of_enum_string.py

Lines changed: 13 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -12,130 +12,31 @@
1212
""" # noqa: E501
1313

1414

15-
from __future__ import annotations
16-
from inspect import getfullargspec
1715
import json
1816
import pprint
1917
import re # noqa: F401
18+
from aenum import Enum, no_arg
2019

21-
from typing import Any, List, Optional
22-
from pydantic import BaseModel, Field, StrictStr, ValidationError, validator
23-
from petstore_api.models.enum_string1 import EnumString1
24-
from petstore_api.models.enum_string2 import EnumString2
25-
from typing import Union, Any, List, TYPE_CHECKING
26-
from pydantic import StrictStr, Field
2720

28-
ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"]
2921

30-
class OneOfEnumString(BaseModel):
22+
23+
24+
class OneOfEnumString(str, Enum):
3125
"""
3226
oneOf enum strings
3327
"""
34-
# data type: EnumString1
35-
oneof_schema_1_validator: Optional[EnumString1] = None
36-
# data type: EnumString2
37-
oneof_schema_2_validator: Optional[EnumString2] = None
38-
if TYPE_CHECKING:
39-
actual_instance: Union[EnumString1, EnumString2]
40-
else:
41-
actual_instance: Any
42-
one_of_schemas: List[str] = Field(ONEOFENUMSTRING_ONE_OF_SCHEMAS, const=True)
43-
44-
class Config:
45-
validate_assignment = True
46-
47-
def __init__(self, *args, **kwargs) -> None:
48-
if args:
49-
if len(args) > 1:
50-
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
51-
if kwargs:
52-
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
53-
super().__init__(actual_instance=args[0])
54-
else:
55-
super().__init__(**kwargs)
5628

57-
@validator('actual_instance')
58-
def actual_instance_must_validate_oneof(cls, v):
59-
instance = OneOfEnumString.construct()
60-
error_messages = []
61-
match = 0
62-
# validate data type: EnumString1
63-
if not isinstance(v, EnumString1):
64-
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`")
65-
else:
66-
match += 1
67-
# validate data type: EnumString2
68-
if not isinstance(v, EnumString2):
69-
error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`")
70-
else:
71-
match += 1
72-
if match > 1:
73-
# more than 1 match
74-
raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
75-
elif match == 0:
76-
# no match
77-
raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
78-
else:
79-
return v
80-
81-
@classmethod
82-
def from_dict(cls, obj: dict) -> OneOfEnumString:
83-
return cls.from_json(json.dumps(obj))
29+
"""
30+
allowed enum values
31+
"""
32+
A = 'a'
33+
B = 'b'
34+
C = 'c'
35+
D = 'd'
8436

8537
@classmethod
8638
def from_json(cls, json_str: str) -> OneOfEnumString:
87-
"""Returns the object represented by the json string"""
88-
instance = OneOfEnumString.construct()
89-
error_messages = []
90-
match = 0
91-
92-
# deserialize data into EnumString1
93-
try:
94-
instance.actual_instance = EnumString1.from_json(json_str)
95-
match += 1
96-
except (ValidationError, ValueError) as e:
97-
error_messages.append(str(e))
98-
# deserialize data into EnumString2
99-
try:
100-
instance.actual_instance = EnumString2.from_json(json_str)
101-
match += 1
102-
except (ValidationError, ValueError) as e:
103-
error_messages.append(str(e))
104-
105-
if match > 1:
106-
# more than 1 match
107-
raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
108-
elif match == 0:
109-
# no match
110-
raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages))
111-
else:
112-
return instance
113-
114-
def to_json(self) -> str:
115-
"""Returns the JSON representation of the actual instance"""
116-
if self.actual_instance is None:
117-
return "null"
118-
119-
to_json = getattr(self.actual_instance, "to_json", None)
120-
if callable(to_json):
121-
return self.actual_instance.to_json()
122-
else:
123-
return json.dumps(self.actual_instance)
124-
125-
def to_dict(self) -> dict:
126-
"""Returns the dict representation of the actual instance"""
127-
if self.actual_instance is None:
128-
return None
129-
130-
to_dict = getattr(self.actual_instance, "to_dict", None)
131-
if callable(to_dict):
132-
return self.actual_instance.to_dict()
133-
else:
134-
# primitive type
135-
return self.actual_instance
136-
137-
def to_str(self) -> str:
138-
"""Returns the string representation of the actual instance"""
139-
return pprint.pformat(self.dict())
39+
"""Create an instance of OneOfEnumString from a JSON string"""
40+
return OneOfEnumString(json.loads(json_str))
14041

14142

samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/with_nested_one_of.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,6 @@ def to_dict(self):
5959
# override the default output from pydantic by calling `to_dict()` of nested_pig
6060
if self.nested_pig:
6161
_dict['nested_pig'] = self.nested_pig.to_dict()
62-
# override the default output from pydantic by calling `to_dict()` of nested_oneof_enum_string
63-
if self.nested_oneof_enum_string:
64-
_dict['nested_oneof_enum_string'] = self.nested_oneof_enum_string.to_dict()
6562
return _dict
6663

6764
@classmethod
@@ -76,7 +73,7 @@ def from_dict(cls, obj: dict) -> WithNestedOneOf:
7673
_obj = WithNestedOneOf.parse_obj({
7774
"size": obj.get("size"),
7875
"nested_pig": Pig.from_dict(obj.get("nested_pig")) if obj.get("nested_pig") is not None else None,
79-
"nested_oneof_enum_string": OneOfEnumString.from_dict(obj.get("nested_oneof_enum_string")) if obj.get("nested_oneof_enum_string") is not None else None
76+
"nested_oneof_enum_string": obj.get("nested_oneof_enum_string")
8077
})
8178
return _obj
8279

0 commit comments

Comments
 (0)