19

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)
Newb
  • 2,810
  • 3
  • 21
  • 35
  • 3
    `type(some_object)` lets you find out the type of an object. Print that and see if you can import it from `requests`. Hint: you can. Also `request.json()` directly does the json loading for you. No need to do it manually. – Wombatz Mar 22 '17 at 03:19

1 Answers1

24

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • What do i need to import for this to work? I am getting `Name 'requests' is not defined`. It works if i do `import requests` but not if I do `from requests import Session`. What do I need to specify? – Jdban101 Jun 22 '17 at 23:34
  • For the above you would want `from requests import Response` and foo would be defined as foo(request: Response) if you just have `import requests` foo would be defined as foo(request: requests.models.Response) – cathaldi Feb 27 '19 at 16:58
  • If it wasn't already clear, `requests.Response == requests.models.Response` – Sean Breckenridge Aug 30 '19 at 05:01
  • Where is `requests` defined in the Django repo? – Anthony To Jul 20 '22 at 03:14