gpt4 book ai didi

Python 类型注解 : Proper way to annotate functions returning library object

转载 作者:行者123 更新时间:2023-12-05 04:29:21 24 4
gpt4 key购买 nike

在此代码中注释类型函数返回的正确方法是什么?

from requests import Request, Session

def make_request(method: str, url: str) -> ??? : # Response object will be returned
request = Request(method, url).prepare()
session = Session()
r = session.send(request)
return r

应该为此导入Response,还是应该使用TypeVar

最佳答案

我认为您应该导入 Response 并使用它。创建 TypeVar 无缘无故地使输入复杂化:

  1. 如果您的模块已经在某处使用了Response(并因此被导入),您甚至不会考虑不将它用于类型提示。
  2. 如果稍后向该模块引入另一个函数或其他内容,并且在那里需要 Response 类,您将遇到 TypeVar 与实际 Response< 不匹配的情况s
  3. 如果您的模块是由另一个模块(甚至是第三方模块)导入的,返回 Response 伪装成自定义 TypeVar 的函数会使代码更加困惑。

关于Python 类型注解 : Proper way to annotate functions returning library object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72336455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com