Skip to content

Commit

Permalink
fix(python): update deserialization templates and typing issues (gene…
Browse files Browse the repository at this point in the history
…rated)

algolia/api-clients-automation#3780

Co-authored-by: algolia-bot <accounts+algolia-api-client-bot@algolia.com>
Co-authored-by: Clément Vannicatte <vannicattec@gmail.com>
  • Loading branch information
algolia-bot and shortcuts committed Sep 24, 2024
1 parent 19f8d7e commit a74db55
Show file tree
Hide file tree
Showing 506 changed files with 11,395 additions and 19,530 deletions.
5 changes: 3 additions & 2 deletions algoliasearch/abtesting/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
from urllib.parse import quote

from pydantic import Field, StrictInt, StrictStr
from typing_extensions import Annotated

if version_info >= (3, 11):
from typing import Annotated, Self
from typing import Self
else:
from typing_extensions import Annotated, Self
from typing_extensions import Self

from algoliasearch.abtesting.config import AbtestingConfig
from algoliasearch.abtesting.models.ab_test import ABTest
Expand Down
119 changes: 42 additions & 77 deletions algoliasearch/abtesting/models/ab_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@

from json import loads
from sys import version_info
from typing import Any, Dict, List, Optional, Union
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
from pydantic import BaseModel, ConfigDict, Field

if version_info >= (3, 11):
from typing import Self
Expand All @@ -28,113 +28,78 @@ class ABTest(BaseModel):
ABTest
"""

ab_test_id: StrictInt = Field(
description="Unique A/B test identifier.", alias="abTestID"
)
click_significance: Optional[Union[StrictFloat, StrictInt]] = Field(
default=None, alias="clickSignificance"
)
conversion_significance: Optional[Union[StrictFloat, StrictInt]] = Field(
ab_test_id: int = Field(alias="abTestID")
""" Unique A/B test identifier. """
click_significance: Optional[float] = Field(default=None, alias="clickSignificance")
conversion_significance: Optional[float] = Field(
default=None, alias="conversionSignificance"
)
add_to_cart_significance: Optional[Union[StrictFloat, StrictInt]] = Field(
add_to_cart_significance: Optional[float] = Field(
default=None, alias="addToCartSignificance"
)
purchase_significance: Optional[Union[StrictFloat, StrictInt]] = Field(
purchase_significance: Optional[float] = Field(
default=None, alias="purchaseSignificance"
)
revenue_significance: Optional[Dict[str, Union[StrictFloat, StrictInt]]] = Field(
revenue_significance: Optional[Dict[str, float]] = Field(
default=None, alias="revenueSignificance"
)
updated_at: StrictStr = Field(
description="Date and time when the A/B test was last updated, in RFC 3339 format.",
alias="updatedAt",
)
created_at: StrictStr = Field(
description="Date and time when the A/B test was created, in RFC 3339 format.",
alias="createdAt",
)
end_at: StrictStr = Field(
description="End date and time of the A/B test, in RFC 3339 format.",
alias="endAt",
)
name: StrictStr = Field(description="A/B test name.")
status: Status
variants: List[Variant] = Field(
description="A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control. "
updated_at: str = Field(alias="updatedAt")
""" Date and time when the A/B test was last updated, in RFC 3339 format. """
created_at: str = Field(alias="createdAt")
""" Date and time when the A/B test was created, in RFC 3339 format. """
end_at: str = Field(alias="endAt")
""" End date and time of the A/B test, in RFC 3339 format. """
name: str = Field(alias="name")
""" A/B test name. """
status: Status = Field(alias="status")
variants: List[Variant] = Field(alias="variants")
""" A/B test variants. The first variant is your _control_ index, typically your production index. The second variant is an index with changed settings that you want to test against the control. """
configuration: Optional[ABTestConfiguration] = Field(
default=None, alias="configuration"
)
configuration: Optional[ABTestConfiguration] = None

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

def to_json(self) -> str:
return self.model_dump_json(by_alias=True, exclude_unset=True)

@classmethod
def from_json(cls, json_str: str) -> Self:
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ABTest from a JSON string"""
return cls.from_dict(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.
"""
_dict = self.model_dump(
"""Return the dictionary representation of the model using alias."""
return self.model_dump(
by_alias=True,
exclude={},
exclude_none=True,
exclude_unset=True,
)
_items = []
if self.variants:
for _item in self.variants:
if _item:
_items.append(_item.to_dict())
_dict["variants"] = _items
if self.configuration:
_dict["configuration"] = self.configuration.to_dict()
return _dict

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

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

_obj = cls.model_validate(
{
"abTestID": obj.get("abTestID"),
"clickSignificance": obj.get("clickSignificance"),
"conversionSignificance": obj.get("conversionSignificance"),
"addToCartSignificance": obj.get("addToCartSignificance"),
"purchaseSignificance": obj.get("purchaseSignificance"),
"revenueSignificance": obj.get("revenueSignificance"),
"updatedAt": obj.get("updatedAt"),
"createdAt": obj.get("createdAt"),
"endAt": obj.get("endAt"),
"name": obj.get("name"),
"status": obj.get("status"),
"variants": (
[Variant.from_dict(_item) for _item in obj.get("variants")]
if obj.get("variants") is not None
else None
),
"configuration": (
ABTestConfiguration.from_dict(obj.get("configuration"))
if obj.get("configuration") is not None
else None
),
}
obj["status"] = obj.get("status")
obj["variants"] = (
[Variant.from_dict(_item) for _item in obj["variants"]]
if obj.get("variants") is not None
else None
)
return _obj
obj["configuration"] = (
ABTestConfiguration.from_dict(obj["configuration"])
if obj.get("configuration") is not None
else None
)

return cls.model_validate(obj)
68 changes: 25 additions & 43 deletions algoliasearch/abtesting/models/ab_test_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,76 +30,58 @@ class ABTestConfiguration(BaseModel):
A/B test configuration.
"""

outliers: Outliers
outliers: Outliers = Field(alias="outliers")
empty_search: Optional[EmptySearch] = Field(default=None, alias="emptySearch")
minimum_detectable_effect: Optional[MinimumDetectableEffect] = Field(
default=None, alias="minimumDetectableEffect"
)

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

def to_json(self) -> str:
return self.model_dump_json(by_alias=True, exclude_unset=True)

@classmethod
def from_json(cls, json_str: str) -> Self:
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ABTestConfiguration from a JSON string"""
return cls.from_dict(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.
"""
_dict = self.model_dump(
"""Return the dictionary representation of the model using alias."""
return self.model_dump(
by_alias=True,
exclude={},
exclude_none=True,
exclude_unset=True,
)
if self.outliers:
_dict["outliers"] = self.outliers.to_dict()
if self.empty_search:
_dict["emptySearch"] = self.empty_search.to_dict()
if self.minimum_detectable_effect:
_dict["minimumDetectableEffect"] = self.minimum_detectable_effect.to_dict()
return _dict

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

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

_obj = cls.model_validate(
{
"outliers": (
Outliers.from_dict(obj.get("outliers"))
if obj.get("outliers") is not None
else None
),
"emptySearch": (
EmptySearch.from_dict(obj.get("emptySearch"))
if obj.get("emptySearch") is not None
else None
),
"minimumDetectableEffect": (
MinimumDetectableEffect.from_dict(
obj.get("minimumDetectableEffect")
)
if obj.get("minimumDetectableEffect") is not None
else None
),
}
obj["outliers"] = (
Outliers.from_dict(obj["outliers"])
if obj.get("outliers") is not None
else None
)
obj["emptySearch"] = (
EmptySearch.from_dict(obj["emptySearch"])
if obj.get("emptySearch") is not None
else None
)
return _obj
obj["minimumDetectableEffect"] = (
MinimumDetectableEffect.from_dict(obj["minimumDetectableEffect"])
if obj.get("minimumDetectableEffect") is not None
else None
)

return cls.model_validate(obj)
52 changes: 17 additions & 35 deletions algoliasearch/abtesting/models/ab_test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@

from json import loads
from sys import version_info
from typing import Any, Dict
from typing import Any, Dict, Optional

from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from pydantic import BaseModel, ConfigDict, Field

if version_info >= (3, 11):
from typing import Self
Expand All @@ -23,61 +23,43 @@ class ABTestResponse(BaseModel):
ABTestResponse
"""

index: StrictStr = Field(
description="Index name of the A/B test variant (case-sensitive)."
)
ab_test_id: StrictInt = Field(
description="Unique A/B test identifier.", alias="abTestID"
)
task_id: StrictInt = Field(
description="Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task's progress with the [`task` operation](#tag/Indices/operation/getTask) and this `taskID`. ",
alias="taskID",
)
index: str = Field(alias="index")
""" Index name of the A/B test variant (case-sensitive). """
ab_test_id: int = Field(alias="abTestID")
""" Unique A/B test identifier. """
task_id: int = Field(alias="taskID")
""" Unique identifier of a task. A successful API response means that a task was added to a queue. It might not run immediately. You can check the task's progress with the [`task` operation](#tag/Indices/operation/getTask) and this `taskID`. """

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

def to_json(self) -> str:
return self.model_dump_json(by_alias=True, exclude_unset=True)

@classmethod
def from_json(cls, json_str: str) -> Self:
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ABTestResponse from a JSON string"""
return cls.from_dict(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.
"""
_dict = self.model_dump(
"""Return the dictionary representation of the model using alias."""
return self.model_dump(
by_alias=True,
exclude={},
exclude_none=True,
exclude_unset=True,
)
return _dict

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

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

_obj = cls.model_validate(
{
"index": obj.get("index"),
"abTestID": obj.get("abTestID"),
"taskID": obj.get("taskID"),
}
)
return _obj
return cls.model_validate(obj)
Loading

0 comments on commit a74db55

Please sign in to comment.