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
7 changes: 7 additions & 0 deletions .chronus/changes/python-array-encode-2025-11-5-10-12-9.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: feature
packages:
- "@typespec/http-client-python"
---

Support encode for array of string in serialization and deserialization
1 change: 1 addition & 0 deletions packages/http-client-python/emitter/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ function emitProperty(
flatten: property.flatten,
isMultipartFileInput: isMultipartFileInput,
xmlMetadata: getXmlMetadata(property),
encode: property.encode,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(
self.is_multipart_file_input: bool = yaml_data.get("isMultipartFileInput", False)
self.flatten = self.yaml_data.get("flatten", False) and not getattr(self.type, "flattened_property", False)
self.original_tsp_name: Optional[str] = self.yaml_data.get("originalTspName")
self.encode: Optional[str] = self.yaml_data.get("encode")

def pylint_disable(self) -> str:
retval: str = ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,8 @@ def declare_property(self, prop: Property) -> str:
args.append("is_multipart_file_input=True")
elif hasattr(prop.type, "encode") and prop.type.encode: # type: ignore
args.append(f'format="{prop.type.encode}"') # type: ignore
elif prop.encode:
args.append(f'format="{prop.encode}"')

if prop.xml_metadata:
args.append(f"xml={prop.xml_metadata}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,19 @@ _VALID_RFC7231 = re.compile(
r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT"
)

_ARRAY_ENCODE_MAPPING = {
"pipeDelimited": "|",
"spaceDelimited": " ",
"commaDelimited": ",",
"newlineDelimited": "\n",
}

def _deserialize_array_encoded(delimit: str, attr):
if isinstance(attr, str):
if attr == "":
return []
return attr.split(delimit)
return attr

def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime:
"""Deserialize ISO-8601 formatted string into Datetime object.
Expand Down Expand Up @@ -323,6 +336,8 @@ _DESERIALIZE_MAPPING_WITHFORMAT = {
def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None):
if annotation is int and rf and rf._format == "str":
return _deserialize_int_as_str
if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING:
return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format])
if rf and rf._format:
return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format)
{% if code_model.has_external_type %}
Expand Down Expand Up @@ -497,6 +512,8 @@ def _is_model(obj: typing.Any) -> bool:

def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements
if isinstance(o, list):
if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o):
return _ARRAY_ENCODE_MAPPING[format].join(o)
return [_serialize(x, format) for x in o]
if isinstance(o, dict):
return {k: _serialize(v, format) for k, v in o.items()}
Expand Down Expand Up @@ -809,6 +826,17 @@ def _deserialize_sequence(
return obj
if isinstance(obj, ET.Element):
obj = list(obj)
try:
if (
isinstance(obj, str)
and isinstance(deserializer, functools.partial)
and isinstance(deserializer.args[0], functools.partial)
and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable
):
# encoded string may be deserialized to sequence
return deserializer(obj)
except: # pylint: disable=bare-except
pass
return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import pytest
from encode.array.aio import ArrayClient
from encode.array import models


@pytest.fixture
async def client():
async with ArrayClient() as client:
yield client


@pytest.mark.asyncio
async def test_comma_delimited(client: ArrayClient):
body = models.CommaDelimitedArrayProperty(value=["blue", "red", "green"])
result = await client.property.comma_delimited(body)
assert result.value == ["blue", "red", "green"]


@pytest.mark.asyncio
async def test_space_delimited(client: ArrayClient):
body = models.SpaceDelimitedArrayProperty(value=["blue", "red", "green"])
result = await client.property.space_delimited(body)
assert result.value == ["blue", "red", "green"]


@pytest.mark.asyncio
async def test_pipe_delimited(client: ArrayClient):
body = models.PipeDelimitedArrayProperty(value=["blue", "red", "green"])
result = await client.property.pipe_delimited(body)
assert result.value == ["blue", "red", "green"]


@pytest.mark.asyncio
async def test_newline_delimited(client: ArrayClient):
body = models.NewlineDelimitedArrayProperty(value=["blue", "red", "green"])
result = await client.property.newline_delimited(body)
assert result.value == ["blue", "red", "green"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import pytest
from encode.array import ArrayClient, models


@pytest.fixture
def client():
with ArrayClient() as client:
yield client


def test_comma_delimited(client: ArrayClient):
body = models.CommaDelimitedArrayProperty(value=["blue", "red", "green"])
result = client.property.comma_delimited(body)
assert result.value == ["blue", "red", "green"]


def test_space_delimited(client: ArrayClient):
body = models.SpaceDelimitedArrayProperty(value=["blue", "red", "green"])
result = client.property.space_delimited(body)
assert result.value == ["blue", "red", "green"]


def test_pipe_delimited(client: ArrayClient):
body = models.PipeDelimitedArrayProperty(value=["blue", "red", "green"])
result = client.property.pipe_delimited(body)
assert result.value == ["blue", "red", "green"]


def test_newline_delimited(client: ArrayClient):
body = models.NewlineDelimitedArrayProperty(value=["blue", "red", "green"])
result = client.property.newline_delimited(body)
assert result.value == ["blue", "red", "green"]
Loading
Loading