在此代码中注释类型函数返回的正确方法是什么?
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
无缘无故地使输入复杂化:
- 如果您的模块已经在某处使用了
Response
(并因此被导入),您甚至不会考虑不将它用于类型提示。 - 如果稍后向该模块引入另一个函数或其他内容,并且在那里需要
Response
类,您将遇到TypeVar
与实际Response< 不匹配的情况
s - 如果您的模块是由另一个模块(甚至是第三方模块)导入的,返回
Response
伪装成自定义TypeVar
的函数会使代码更加困惑。
关于Python 类型注解 : Proper way to annotate functions returning library object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72336455/