如何在PyCharm + python2.7中指定泛型返回类型

时间:2017-03-28 16:20:28

标签: python pycharm typing docstring

如何在以下函数中定义docstring?

def get_object(klass, **kwargs):
    """
    :rtype: ???
    """
    # perform some tasks
    return klass(**kwargs)

我已尝试klasstype(klass)klass.__class__, 它们都不能在分离的模块文件中工作:

from sample.utils import get_object
from sample.models import User

u = get_object(User, name='test')
u.  # no PyCharm hint here

我也尝试了:type klass: T:rtype: T,也没有工作:(

PyCharm可以在docstring中支持这种语法吗? 如何记录?

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

def get_obj(klass, **kwargs):
"""
:type klass: ((object) -> T) | T
:type kwargs: object
:rtype: T
"""

Class可以是__init__的lambda,因此可以使用lambda的返回类型作为类的实例类型