Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 959
Newb Avatar asked Mar 22 '17 00:03

Newb


People also ask

What are type hints?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

What is any type in Python?

The purpose of the Any type is to indicate to the type checker that a part of the program should not be checked. A variable (or function parameter) that is annotated with the Any type accepts any value, and the type checker allows any operation on it.

Why is MYPY so slow?

Mypy runs are slow If your mypy runs feel slow, you should probably use the mypy daemon, which can speed up incremental mypy runtimes by a factor of 10 or more. Remote caching can make cold mypy runs several times faster.

How do you type hints in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.


1 Answers

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.

like image 99
Dimitris Fasarakis Hilliard Avatar answered Sep 20 '22 12:09

Dimitris Fasarakis Hilliard