如何为方法响应生成typehint,其中响应取决于python中的方法参数? 我的意图
因此,我正在为一个服务开发一个API包。我想为我的库中存在的每个方法生成好的类型提示 例如,当用户键入如何为方法响应生成typehint,其中响应取决于python中的方法参数? 我的意图,python,pycharm,type-hinting,typing,python-typing,Python,Pycharm,Type Hinting,Typing,Python Typing,因此,我正在为一个服务开发一个API包。我想为我的库中存在的每个方法生成好的类型提示 例如,当用户键入get().时,dot pycharm会让他知道此方法将提供什么响应 e、 g: 陷阱 但是,有一些方法根据方法中的参数提供不同的响应。 e、 g 对象结构 现在我有了这样的结构(我没有简化) 问题 问题是,当我键入get(fields='firsttname').response.items[0]时,pycharm仅为int显示类型提示。他认为,条目不能包含List[UserInfo],他认为
get().
时,dot pycharm会让他知道此方法将提供什么响应
e、 g:
陷阱
但是,有一些方法根据方法中的参数提供不同的响应。
e、 g
对象结构
现在我有了这样的结构(我没有简化)
问题
问题是,当我键入get(fields='firsttname').response.items[0]时,
pycharm仅为int
显示类型提示。他认为,条目不能包含List[UserInfo]
,他认为,它只能包含List[int]
我试过了 我曾尝试使用typing.重载装饰器,但方法“get”有许多参数,实际上不支持默认参数值。也许我做得不好 这里是我用重载(simlified)尝试的内容。它之所以不起作用是因为“某些其他参数”,但我把它放在这里以防万一:
from typing import overload
@overload
def get(fields: None) -> GetResponseNoFields: ...
@overload
def get(fields: str) -> GetResponseWithFields: ...
def get(some_other_param=None, fields=None):
# code here
pass
当我尝试调用不带参数的方法时,pycharm说,“一些参数未填充”完整签名应该在每个重载中重复完整签名应该在每个重载中重复完整签名
# this method responses with object, containing fields:
# count - count of items
# items - list of ids of users
info = get()
# but this method will give additional information. It responses with object, containing fields:
# count - count of items
# items - list of objects with users' information. It has fields:
# id - id of user
# firstname - firstname of user
# lastname - lastname of user
# ... and some others
info = get(fields='firstname')
from typing import List, Union
from pydantic import BaseModel, Field
class UserInfo(BaseModel):
id: int = Field(...)
firstname: str = Field(None)
lastname: str = Field(None)
some_other_fields: str = Field(None)
class GetResponseNoFields(BaseModel):
count: int = Field(...)
items: List[int] = Field(...)
class GetResponseWithFields(BaseModel):
count: int = Field(...)
items: List[UserInfo] = Field(...)
class GetResponseModel(BaseModel):
response: Union[GetResponseNoFields, GetResponseWithFields] = Field(...)
def get(fields=None) -> GetResponseModel:
# some code
pass
from typing import overload
@overload
def get(fields: None) -> GetResponseNoFields: ...
@overload
def get(fields: str) -> GetResponseWithFields: ...
def get(some_other_param=None, fields=None):
# code here
pass