Skip to content
Merged
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
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Fix for optional properties in flatten model to keep compatibility
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,11 @@ class _RestField:

@property
def _class_type(self) -> typing.Any:
return getattr(self._type, "args", [None])[0]
result = getattr(self._type, "args", [None])[0]
# type may be wrapped by nested functools.partial so we need to check for that
if isinstance(result, functools.partial):
return getattr(result, "args", [None])[0]
return result

@property
def _rest_name(self) -> str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
from typing import (
Any,
Mapping,
Optional,
overload,
)

from specs.azure.clientgenerator.core.flattenproperty._utils.model_base import (
Model,
rest_field,
)
from azure.core.serialization import attribute_list


class ModelProperty(Model):
Expand Down Expand Up @@ -179,3 +181,71 @@ def test_model_initialization():
2023, 1, 12, 0, 0, 0, tzinfo=datetime.timezone.utc
)
assert model.properties["datetimeUnixTimestamp"] == 1673481600


class FlattenModelWithOptionalProperties(Model):
"""This is the model with one level of flattening and optional properties."""

name: str = rest_field()
"""Required."""
properties: Optional["ModelProperty"] = rest_field()
"""Optional."""

__flattened_items = ["value"]

@overload
def __init__(
self,
*,
name: str,
properties: Optional["ModelProperty"],
) -> None: ...

@overload
def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""

def __init__(self, *args: Any, **kwargs: Any) -> None:
_flattened_input = {k: kwargs.pop(k) for k in kwargs.keys() & self.__flattened_items}
super().__init__(*args, **kwargs)
for k, v in _flattened_input.items():
setattr(self, k, v)

def __getattr__(self, name: str) -> Any:
if name in self.__flattened_items:
if self.properties is None:
return None
return getattr(self.properties, name)
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")

def __setattr__(self, key: str, value: Any) -> None:
if key in self.__flattened_items:
if self.properties is None:
self.properties = self._attr_to_rest_field["properties"]._class_type()
setattr(self.properties, key, value)
else:
super().__setattr__(key, value)


def test_model_with_optional_properties_initialization():
model = FlattenModelWithOptionalProperties(
name="test",
value="test value",
)

assert model.name == "test"

assert model.value == "test value"
assert model.properties.value == "test value"


def test_model_with_optional_properties_attribute_list():
model = FlattenModelWithOptionalProperties(
name="test",
)

attrs = attribute_list(model)
assert sorted(attrs) == sorted(["name", "value"])
Loading