Skip to content

Commit

Permalink
[python-nextgen] support constructor with position argument in oneOf/…
Browse files Browse the repository at this point in the history
…anyOf model (#15434)

* support position constructor

* update samples

* update test
  • Loading branch information
wing328 committed May 8, 2023
1 parent 72cb03b commit b4eb707
Show file tree
Hide file tree
Showing 29 changed files with 662 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,24 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}

def __init__(self, *args, **kwargs):
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
if kwargs:
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@validator('actual_instance')
def actual_instance_must_validate_anyof(cls, v):
{{#isNullable}}
if v is None:
return v

{{/isNullable}}
instance = cls()
instance = {{{classname}}}.construct()
error_messages = []
{{#composedSchemas.anyOf}}
# validate data type: {{{dataType}}}
Expand Down Expand Up @@ -74,7 +84,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/composedSchemas.anyOf}}
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages))
else:
return v

Expand All @@ -85,7 +95,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
"""Returns the object represented by the json string"""
instance = cls()
instance = {{{classname}}}.construct()
{{#isNullable}}
if json_str is None:
return instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,24 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}

def __init__(self, *args, **kwargs):
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
if kwargs:
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@validator('actual_instance')
def actual_instance_must_validate_oneof(cls, v):
{{#isNullable}}
if v is None:
return v

{{/isNullable}}
instance = cls()
instance = {{{classname}}}.construct()
error_messages = []
match = 0
{{#composedSchemas.oneOf}}
Expand All @@ -68,16 +78,15 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`")
else:
match += 1

{{/isPrimitiveType}}
{{/isContainer}}
{{/composedSchemas.oneOf}}
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages))
else:
return v

Expand All @@ -88,7 +97,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
@classmethod
def from_json(cls, json_str: str) -> {{{classname}}}:
"""Returns the object represented by the json string"""
instance = cls()
instance = {{{classname}}}.construct()
{{#isNullable}}
if json_str is None:
return instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2194,3 +2194,8 @@ components:
properties:
optionalDict:
$ref: "#/components/schemas/DictWithAdditionalProperties"
IntOrString:
oneOf:
- type: integer
minimum: 10
- type: string
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ docs/FormatTest.md
docs/HasOnlyReadOnly.md
docs/HealthCheckResult.md
docs/InnerDictWithProperty.md
docs/IntOrString.md
docs/List.md
docs/MapTest.md
docs/MixedPropertiesAndAdditionalPropertiesClass.md
Expand Down Expand Up @@ -130,6 +131,7 @@ petstore_api/models/format_test.py
petstore_api/models/has_only_read_only.py
petstore_api/models/health_check_result.py
petstore_api/models/inner_dict_with_property.py
petstore_api/models/int_or_string.py
petstore_api/models/list.py
petstore_api/models/map_test.py
petstore_api/models/mixed_properties_and_additional_properties_class.py
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ Class | Method | HTTP request | Description
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [HealthCheckResult](docs/HealthCheckResult.md)
- [InnerDictWithProperty](docs/InnerDictWithProperty.md)
- [IntOrString](docs/IntOrString.md)
- [List](docs/List.md)
- [MapTest](docs/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# IntOrString


## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------

## Example

```python
from petstore_api.models.int_or_string import IntOrString

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

# convert the object into a dict
int_or_string_dict = int_or_string_instance.to_dict()
# create an instance of IntOrString from a dict
int_or_string_form_dict = int_or_string.from_dict(int_or_string_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 @@ -75,6 +75,7 @@
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
from petstore_api.models.has_only_read_only import HasOnlyReadOnly
from petstore_api.models.health_check_result import HealthCheckResult
from petstore_api.models.inner_dict_with_property import InnerDictWithProperty
from petstore_api.models.int_or_string import IntOrString
from petstore_api.models.list import List
from petstore_api.models.map_test import MapTest
from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,19 @@ class AnyOfColor(BaseModel):
class Config:
validate_assignment = True

def __init__(self, *args, **kwargs):
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
if kwargs:
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@validator('actual_instance')
def actual_instance_must_validate_anyof(cls, v):
instance = cls()
instance = AnyOfColor.construct()
error_messages = []
# validate data type: List[int]
try:
Expand All @@ -66,7 +76,7 @@ def actual_instance_must_validate_anyof(cls, v):
error_messages.append(str(e))
if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v

Expand All @@ -77,7 +87,7 @@ def from_dict(cls, obj: dict) -> AnyOfColor:
@classmethod
def from_json(cls, json_str: str) -> AnyOfColor:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfColor.construct()
error_messages = []
# deserialize data into List[int]
try:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,19 @@ class AnyOfPig(BaseModel):
class Config:
validate_assignment = True

def __init__(self, *args, **kwargs):
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
if kwargs:
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@validator('actual_instance')
def actual_instance_must_validate_anyof(cls, v):
instance = cls()
instance = AnyOfPig.construct()
error_messages = []
# validate data type: BasquePig
if not isinstance(v, BasquePig):
Expand All @@ -60,7 +70,7 @@ def actual_instance_must_validate_anyof(cls, v):

if error_messages:
# no match
raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages))
else:
return v

Expand All @@ -71,7 +81,7 @@ def from_dict(cls, obj: dict) -> AnyOfPig:
@classmethod
def from_json(cls, json_str: str) -> AnyOfPig:
"""Returns the object represented by the json string"""
instance = cls()
instance = AnyOfPig.construct()
error_messages = []
# anyof_schema_1_validator: Optional[BasquePig] = None
try:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,22 @@ class Color(BaseModel):
class Config:
validate_assignment = True

def __init__(self, *args, **kwargs):
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
if kwargs:
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
super().__init__(actual_instance=args[0])
else:
super().__init__(**kwargs)

@validator('actual_instance')
def actual_instance_must_validate_oneof(cls, v):
if v is None:
return v

instance = cls()
instance = Color.construct()
error_messages = []
match = 0
# validate data type: List[int]
Expand All @@ -69,10 +79,10 @@ def actual_instance_must_validate_oneof(cls, v):
error_messages.append(str(e))
if match > 1:
# more than 1 match
raise ValueError("Multiple matches found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
raise ValueError("Multiple matches found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
elif match == 0:
# no match
raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages))
else:
return v

Expand All @@ -83,7 +93,7 @@ def from_dict(cls, obj: dict) -> Color:
@classmethod
def from_json(cls, json_str: str) -> Color:
"""Returns the object represented by the json string"""
instance = cls()
instance = Color.construct()
if json_str is None:
return instance

Expand Down
Loading

0 comments on commit b4eb707

Please sign in to comment.