Type safety: resource methods unpack dict | list HTTP responses with **
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 65/100
- Tipo de issue
- Refactorización
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- python
- Área
- backend-api-design, tooling
Línea de trabajo
Observe los métodos de recursos en modelos como Agent, Contact y Conversation. Estos llaman a self._http.get y desempaquetan la respuesta con Model(**response). Reemplácelos con Model.model_validate(response). También verifique los dos archivos de prueba mencionados para el estrechamiento de tipos. Ejecute ty check . para confirmar que se resuelven los diagnósticos.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Context
This follows #11 (ty as a dev dependency) and #12 (builtins.list annotations), as part of re-enabling ty in CI. Once #12 is in, ty check . reports 42 diagnostics. 40 of them come from the issue below, and I'd like your preference on the fix before opening a PR.
Problem
HTTPClient / AsyncHTTPClient methods return dict[str, Any] | list[Any], which is accurate: _unwrap_response returns a list or a single object depending on the endpoint. Single-object resource methods then unpack the result without checking which one it is:
response = self._http.get(f"/api/v1/accounts/{account_id}/agents/{agent_id}")
return Agent(**response) # ty: argument after ** must be a mapping, found `dict[str, Any] | list[Any]`
This return Model(**response) pattern appears 40 times across 9 models (Agent, Contact, Conversation, Inbox, Team, Message, Profile, ContactCreateResponse, ConversationToggleStatusResponse). It isn't a bug today, since those endpoints do return objects. But the types don't show that, and if a list ever came back, the user would get a bare TypeError. List methods already narrow with isinstance(response, list) and aren't affected.
Options
Model.model_validate(response)(my preference)- One-line change at each of the 40 sites, and
_httpstays untouched. - pydantic already validates the input at runtime, and
model_validateacceptsAny, so the type checker is satisfied. - It behaves the same as today for dict responses, because these models use no aliases or custom config. An unexpected list would raise a pydantic
ValidationErrorinstead of aTypeError.
- One-line change at each of the 40 sites, and
- Split the HTTP methods by response shape, e.g.
get_object() -> dict[str, Any]andget_list() -> list[Any], which check the shape and raise aChatwootAPIErrorotherwise.- This gives the most precise types.
- But it redesigns the internal HTTP API in both clients and touches every call site, including the list ones.
cast(dict[str, Any], response)at each site.- This silences the checker without any runtime check, so I'd rather avoid it.
Also in scope
Two small narrowing fixes in tests:
tests/smoke/test_smoke.py:240:contact.nameisstr | None.tests/unit/test_inbox_agent_bot.py:59: subscripting a possibly-Noneresult.
Once this and #11/#12 are merged, a small follow-up PR would re-enable the ty job in CI.
Note on overlap
#5, #8 and #9 touch some of the same resource files (#8 specifically changes response handling). Happy to rebase onto whichever lands first. Just let me know if one of them should go in before this.
Which option would you prefer?
- Lenguaje dominante
- Python
- Estrellas
- 8
- Forks
- 5
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de chatwoot/chatwoot-sdk-python
-
Dificultad 3/5 1-2 días Aptitud para principiantes 35/100
Todos los issues de chatwoot/chatwoot-sdk-python
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 73/100
Netcracker/qubership-ai-packages#266 ·
Los mantenedores suelen responder en 1 día
-
PROCESSED_DATA_FOLDER: strip whitespace and treat empty as unsetPosiblemente ocupada @TorecLuik la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
NL-BioImaging/BIOMERO.importer#63 ·
Los mantenedores suelen responder en 1 día
-
MLX training-complete chat/merge suggestions omit --backend mlxPosiblemente ocupada @vaputa la tomó hoy. Abiertoneeds-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
MakazhanAlpamys/Soup#2913 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
area:security effort:S priority:P3 status:needs-triage type:chore
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
randomparity/kdive#3657 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
aws/mcp-proxy-for-aws#476 ·
Los mantenedores suelen responder en 1 día