Type safety: resource methods unpack dict | list HTTP responses with **

Offen Anfängerfreundlich
#13 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
65/100
Issue-Typ
Refactoring
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
python

Rechercherichtung

Schauen Sie sich die Ressourcenmethoden in Modellen wie Agent, Contact und Conversation an. Sie rufen self._http.get auf und entpacken die Antwort mit Model(**response). Ersetzen Sie diese durch Model.model_validate(response). Überprüfen Sie auch die beiden erwähnten Testdateien auf Type Narrowing. Führen Sie ty check . aus, um zu überprüfen, ob die Diagnosen behoben sind.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

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

  1. Model.model_validate(response) (my preference)
    • One-line change at each of the 40 sites, and _http stays untouched.
    • pydantic already validates the input at runtime, and model_validate accepts Any, 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 ValidationError instead of a TypeError.
  2. Split the HTTP methods by response shape, e.g. get_object() -> dict[str, Any] and get_list() -> list[Any], which check the shape and raise a ChatwootAPIError otherwise.
    • 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.
  3. 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.name is str | None.
  • tests/unit/test_inbox_agent_bot.py:59: subscripting a possibly-None result.

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?

Vorherrschende Sprache
Python
Sterne
8
Forks
5
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Entwicklungsumgebung

Dieses Projekt bietet weder Dev-Container noch Dockerfile noch Beitragsleitfaden – die Einrichtung liegt bei Ihnen. Beginnen Sie mit der README; die allgemeinen Schritte stehen in unserem Leitfaden für den ersten Beitrag.

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus chatwoot/chatwoot-sdk-python

Alle Issues in chatwoot/chatwoot-sdk-python

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.