我正在Python2.7中试用PEP 0484 type hinting。对于大多数情况,这是相当简单的,但我无意中发现了以下函数。我试过:
from typing import TypeVar, Type, Callable, Union, Dict
T = TypeVar('T')
def ensure_cls(cls):
# type: (Type[T]) -> Callable[[Union[T, Dict]], T]
"""
If the argument is an instance of cls, pass, else try constructing.
"""
def converter(val):
# type: (Union[T, Dict]) -> T
if isinstance(val, cls):
return val
else:
return cls(**val) # 'cls' is not callable
return converter
PyCharm(2017.1.2)抱怨“cls”不可调用。这可能是PyCharm检查的误报,但另一方面,PyCharm确实有一点:并非所有类型都是可调用的。你知道吗
也许有更好的方法来类型提示这个函数并指定cls实际上是一个可调用的类型?你知道吗
在函数上方键入提示的建议方法是什么?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐