Search code examples
pythonpython-requeststypecheckingpython-3.6mypy

MyPy: what is the type of a requests object?


I'm trying to use Python 3's type hinting syntax, along with the MyPy static type checker. I'm now writing a function that takes a requests response object, and I'm wondering how to indicate the type.

That is to say, in the following piece of code, what can I replace ??? with?

import requests

def foo(request: ???) -> str:
    return json.loads(request.content)['some_field']

r = requests.get("my_url")
return foo(r)

Solution

  • By using Response, either supply the full path to it:

    def foo(request: requests.models.Response) -> str:
        return json.loads(request.content)['some_field']
    

    or, save it to a name of your choice:

    Response = requests.models.Response
    
    def foo(request: Response) -> str:
        return json.loads(request.content)['some_field']
    

    p.s json.loads expects a str, not bytes so you might want to decode the content first.