为什么mypy确定参数是可选的

  • 本文关键字:参数 mypy python mypy
  • 更新时间 :
  • 英文 :


我继承了以下代码

import json
from flask import Request, jsonify

def main(request: Request = None):
request_body = {}
if request.is_json:
request_body = request.get_json()
elif request.mimetype == "application/octet-stream":
try:
request_body = json.loads(request.data.decode("utf8"))
except Exception:
pass
# do some other work with request_body...
#...
return jsonify(message="DONE")

if __name__ == "__main__":
main()

我现在正在运行mypy(我目前正在努力自学(,它正在返回这些错误:

google/runtime/modules/RealTimeIngestion/cloudFunctions/translate-schema/translate-schema/main.py:8: error: Item "None" of "Optional[Request]" has no attribute "is_json"
google/runtime/modules/RealTimeIngestion/cloudFunctions/translate-schema/translate-schema/main.py:9: error: Item "None" of "Optional[Request]" has no attribute "get_json"
google/runtime/modules/RealTimeIngestion/cloudFunctions/translate-schema/translate-schema/main.py:9: error: Incompatible types in assignment (expression has type "Optional[Any]", variable has type "Dict[Any, Any]")
google/runtime/modules/RealTimeIngestion/cloudFunctions/translate-schema/translate-schema/main.py:10: error: Item "None" of "Optional[Request]" has no attribute "mimetype"
google/runtime/modules/RealTimeIngestion/cloudFunctions/translate-schema/translate-schema/main.py:12: error: Item "None" of "Optional[Request]" has no attribute "data"

我不明白为什么参数request: Request被解释为可选。我确实想知道这是否是因为

if __name__ == "__main__":
main()

然而,我对此进行了评论,mypy仍然返回了相同的错误。

为什么mypy会提出这些错误?

  • 可选:一旦我们为参数分配了默认值,它就变成了可选的,也就是python_function_default_parameter

  • 错误:当请求试图将None转换为请求类型时,您会收到错误,因为请求应该具有有效值及其抛出错误

最新更新