tuk
tuk

Reputation: 6842

How to add documentation with type hints in class method declaration in Pycharm 2018.2?

Let's say I have a class method like below-

class BasePreStep:
    def __init__(self, threadpool, release_manifest, service_manifest, upgrade_bundle, system_config):

If I add type hint like below then auto-completion works fine in the python file

class BasePreStep:
    __metaclass__ = ABCMeta

    def __init__(self, threadpool, release_manifest, service_manifest, upgrade_bundle, system_config):
        # type: (self, ThreadPool, service_version_pb2.ReleaseManifest, service_version_pb2.ServiceManifest, str, SystemConfig) -> ()

But if I add comments like below (as explained here) then the auto-completion does not work in the python file.

class BasePreStep: metaclass = ABCMeta

def __init__(self, threadpool, release_manifest, service_manifest, upgrade_bundle, system_config):
    """

    :param threadpool: Threadpool
    :param release_manifest: service_version_pb2.ReleaseManifest
    :param service_manifest: service_version_pb2.ServiceManifest
    :param upgrade_bundle: str
    :param system_config: SystemConfig
    """

Can someone let me know what is the recommended way of adding comment along with type hint in Pycharm?

Upvotes: 1

Views: 263

Answers (1)

Mikhail Burshteyn
Mikhail Burshteyn

Reputation: 5002

param in docstrings is treated as a description, not as a type annotation, that's why your second example doesn't work.

You have two options here:

  1. Add descriptions and types to docstring:

    class Class:
        def method(self, p1, p2):
            """
    
            :param p1: parameter 1
            :type p1: str
            :param p2: parameter 2
            :type p2: str
            """
    
  2. Add descriptions to docstring and document types in a type comment (which must go before the docstring, otherwise Pycharm won't recognize it).

    class Class:
        def method(self, p1, p2):
            # type: (str, str) -> None
            """
    
            :param p1: parameter 1
            :param p2: parameter 2
            """
    

Upvotes: 1

Related Questions