pythontyping

Handle Exceptions in Python Function's signature


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:

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?


Solution

  • 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()