I wonder if I have designed my script correctly (it works so far) because of a loop of warnings from which I cannot get out.
I am trying to define a function that either is able to parse a JSON response from a website or it simply terminates the program. Here my code:
from requests import get, Response, JSONDecodeError
from typing import Any
from sys import exit
def logout() -> None:
exit()
def get_page(url:str) -> dict[Any,Any]:
try:
response: Response = get(url)
page: dict[Any,Any] = response.json()
except JSONDecodeError as e:
print(e)
logout()
return page
try:
result: dict[Any, Any] = get_page("https://stackoverflow.com/")
except Exception as e:
#handle exception
pass
print(result['something'])
Pylance informs me that page
(as in return page
) and result
(as in print(result['something']
) is possibly unbound
.
As far as I understand there are different possible workarounds to this problem, but none of them solves entirely the problem:
return page
before the except
statement, mypy
raises a Missing return statement
.mypy
, Pylance informs me that I should anyway sign my function specifying that it should return dict[Any,Any] | None
.dict[Any,Any]
means that outside the function result
should be result: dict[Any,Any]|None
but then result['something'] is possibly unbound
and Object of type "None" is not subscriptable
page = {}
at the beginning of the function is a possible solution, but what if page
is a custom class
which need some parameter that I cannot provide?raise
an Exception
from within the function if there would have been a way to inform Pylance about this possible behaviour (is there?)My point is: the function will NEVER return None
right? So, am I doing something wrong? How do you deal with this? Should I refactor my function?
typing.NoReturn is used for functions that never return. For example:
from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')
So you should type hint the return value of logout()
with NoReturn:
from typing import NoReturn
def logout() -> NoReturn:
exit()