Mypy抛出错误“ Missing return statement”,但我看不到丢失的地方

时间:2019-02-14 09:30:02

标签: python python-requests mypy

我试图在http_requests中实现重试功能,但是我遇到了“需要” return语句的问题,尽管我不知道应该在哪里

def _http_request(method: _HttpMethod, url: str, **kwargs) -> Optional[requests.models.Response]:
    _body: Any = None
    _retries: Any = 3
    if "json" in kwargs:
        _body = kwargs.get("json")
    elif "data" in kwargs:
        _body = kwargs.get("data")
    elif "retries" in kwargs:
        _retries = kwargs.get("retries")
    elif "timeout" in kwargs:
        _timeout = kwargs.get("timeout")

    for _retry in range(1, _retries):
        try:
            logging.debug(f"{method.value} {url} body: {_body}")
            _response = requests.request(method.value, url, **kwargs)
            logging.debug(f"{_response.status_code} body: {_response.text}")
            return _response
        except NewConnectionError:
            logging.error("Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time.")
            return None
        except requests.exceptions.ConnectionError:
            logging.error("Failed to establish a new connection: [Errno 113] No route to host.")
            return None
        except requests.exceptions.Timeout:
            if _retry <= 3:
                logging.warning(f"Connection to Jira timed out after {_timeout}, trying to connect again({_retry} of {_retries} retries)")
            else:
                logging.error(f"Failed to connect to jira server efter {_retries}")
                return None

1 个答案:

答案 0 :(得分:0)

return语句位于for循环内,但不在for循环内,从而导致不一致。

在for循环之外(之后)添加return None

if _retry <= 3:也是不一致的,因为它没有返回语句,但是循环后的return None可以解决警告。