Search code examples
pythonpycharmtypingdocstring

How to specifying generic return type in PyCharm + python2.7


How to define the docstring in following function?

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

I've tried klass, type(klass), klass.__class__, they all didn't work in separated module files:

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

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

I also tried :type klass: T and :rtype: T, also not working :(

Can PyCharm support these kind of syntax in docstring? How to document it?


Solution

  • Try something like this:

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

    Class can be a lambda of its __init__, so you can use lambda's return type as the instance type of a class