Iva*_*hin 8 python django type-hinting pycharm
我有 Django 视图的辅助函数,如下所示(代码如下)。它返回 None 或与给定查询匹配的单个对象(例如pk=1)。
from typing import Type, Optional
from django.db.models import Model
def get_or_none(cls: Type[Model], **kwargs) -> Optinal[Model]:
try:
return cls.objects.get(**kwargs)
except cls.DoesNotExist:
return None
Run Code Online (Sandbox Code Playgroud)
假设我创建了自己的模型(例如Car)及其自己的字段(例如brand,model)。当我将get_or_none函数结果分配给变量,然后检索实例字段时,我在 PyCharm 中收到令人讨厌的未解析引用的警告。
car1 = get_or_none(Car, pk=1)
if car1 is not None:
print(car1.brand) # <- Unresolved attribute reference 'brand' for class 'Model'
Run Code Online (Sandbox Code Playgroud)
消除此警告并获得变量代码完成的正确类型提示是什么?
找到了几乎类似问题的答案。解决方案是使用TypeVar进行输入
from typing import TypeVar, Type, Optional
from django.db.models import Model
T = TypeVar('T', bound=Model)
def get_or_none(cls: Type[T], **kwargs) -> Optional[T]:
... # same code
Run Code Online (Sandbox Code Playgroud)
一切正常:没有警告和代码完成
| 归档时间: |
|
| 查看次数: |
3387 次 |
| 最近记录: |