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)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With