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

标签 python python-3.x annotations python-typing

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

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/

相关文章:

python - 为什么属性属于内置重写描述符类型?

python - Python 3项目结构的最佳实践

python - Flask 如何保持请求全局线程安全

python - 查找并替换引号之间的字符串

python - 从重复出现的单词右侧的 n 个元素形成新列表

python - 如何从 Cython 方法描述符获取参数名称和 __annotations__ ?

java - 为什么 astyanax (java) 无法在我的 scala 案例类参数列表中识别我的 @Id 注释值?

python - 在 Python Zeep 中更改服务 URL

python - 如何在 aerospike 中获取没有元数据的记录

php - 为什么我的 Controller 不工作但抛出 FileLoaderException?