how to type python API responses similar to TS `as`?

Question:

I’m using a lib that types its response as

-> (Unknown | Response | Any)

If i know/expect the response to be a Response and that is has an id field,
how can I cast that in my code?

Typescript provides an as <type> operator for this.

        response = self.client.get_user(username=username)
        user_id = response.data['id']
Cannot access member "data" for type "Response"
  Member "data" is unknownPylancereportGeneralTypeIssues

in addition to the typing.cast I’m looking for a simple way to define the shape of a response, without adding a full class hierarchy just to type a blob of data coming back from a third party API.
Similar to type or even interface in typescript.

It seems the Response object/class isn’t typed.

enter image description here

Asked By: dcsan

||

Answers:

You’re looking for typing.cast

response = cast(Response, self.client.get_user(username=username))
user_id = response.data['id']
Answered By: Silvio Mayolo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.