Skip to content

[python][bug] wrong typing #10524

Closed

Description

@msyyc

For typespec:

import "@typespec/http";

using Http;
@service(#{ title: "Widget Service" })
namespace DemoService;


@route("/widgets")
@tag("Widgets")
interface Widgets {
  /** List widgets */
  @list list(): {@nextLink nextLink: url, @pageItems value: string[][]};
}

Here is generated python sdk code:

# coding=utf-8
from collections.abc import MutableMapping
from typing import Any, Callable, Optional, TypeVar

from corehttp.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from corehttp.paging import AsyncItemPaged, AsyncList
from corehttp.rest import AsyncHttpResponse, HttpRequest
from corehttp.runtime import AsyncPipelineClient
from corehttp.runtime.pipeline import PipelineResponse

from ..._utils.model_base import _deserialize
from ..._utils.serialization import Deserializer, Serializer
from ...operations._operations import build_widgets_list_request
from .._configuration import DemoServiceClientConfiguration

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]]
List = list


class WidgetsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~demoservice.aio.DemoServiceClient`'s
        :attr:`widgets` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: DemoServiceClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    def list(self, **kwargs: Any) -> AsyncItemPaged[list[str]]:
        """List widgets.

        :return: An iterator like instance of list of str
        :rtype: ~corehttp.paging.AsyncItemPaged[list[str]]
        :raises ~corehttp.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[List[str]]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_widgets_list_request(
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                _request = HttpRequest("GET", next_link)
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[List[str]],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

The response typing shall be AsyncItemPaged[List[str]] instead of AsyncItemPaged[list[str]] for operation list

Activity

  1. github-actions commented on Apr 28, 2026

    @github-actions
    Contributor

    🎯 Issue Triage

    The Python client emitter generates an incorrect return type annotation for paginated operations when the page items are arrays (string[][]). The annotation uses list[str] (built-in lowercase) in the return type instead of List[str] (the module-level alias), leading to a naming conflict since the generated method itself is also named list.

    Category: Bug
    Area: emitter:client:python

    🔗 No playground link provided.

    📋 Reproduction code
    import "`@typespec/http`";
    
    using Http;
    `@service`(#{ title: "Widget Service" })
    namespace DemoService;
    
    `@route`("/widgets")
    `@tag`("Widgets")
    interface Widgets {
      /** List widgets */
      `@list` list(): { `@nextLink` nextLink: url, `@pageItems` value: string[][] };
    }
    🔍 Analysis
    • The TypeSpec defines @pageItems value: string[][] — a list of string[] items, so each paged item is list[str].
    • The generated Python operation method is named list, which shadows the built-in list type within the method scope.
    • To work around this, the emitter already emits List = list at module level and uses List[List[str]] inside the extract_data closure.
    • However, the method's return annotation is still written as -> AsyncItemPaged[list[str]] and the docstring :rtype: also uses list[str].
    • While the annotation itself is technically evaluated at class definition scope (where list still refers to the built-in), this inconsistency is confusing and the docstring/annotation should consistently use List[str] to match the rest of the generated code.
    • Affected component: packages/http-client-python — the paging codegen path when array-typed page items are involved.
    📝 Suggested next steps
    • In the Python emitter, when generating return type annotations and docstrings for paged operations, check if the page item type is an array type and consistently use the List alias in all generated references (return annotation, docstring :rtype:, and internal usages).
    • Add a test case covering @pageItems on string[][] (array of arrays) to prevent regression.

    Note

    🔒 Integrity filter blocked 2 items

    The following items were blocked because they don't meet the GitHub integrity level.

    • #10524 issue_read: has lower integrity than agent requires. The agent cannot read data with integrity below "approved".
    • [python][bug] wrong typing #10524 issue_read: has lower integrity than agent requires. The agent cannot read data with integrity below "approved".

    To allow these resources, lower min-integrity in your GitHub frontmatter:

    tools:
      github:
        min-integrity: approved  # merged | approved | unapproved | none

    Generated by Agentic Triage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't workingemitter:client:pythonIssue for the Python client emitter: @typespec/http-client-python

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions