【问题标题】:How to specifying generic return type in PyCharm + python2.7如何在 PyCharm + python2.7 中指定泛型返回类型
【发布时间】:2017-03-28 16:20:28
【问题描述】:

如何在下面的函数中定义文档字符串?

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 中支持这种语法吗? 如何记录?

【问题讨论】:

    标签: python pycharm typing docstring


    【解决方案1】:

    试试这样的:

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

    类可以是它的__init__的一个lambda,所以你可以使用lambda的返回类型作为一个类的实例类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多