Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify class or function type in docstring for PyCharm parser

I use a lot the Pycharm docstring type parser in order to specify the types of the methods parameters and return, the attributes or the instance variable. If it works nearly all the time, I have a little issue about telling PyCharm I am giving a function or a class as parameter/attribute/...

Here is a short example :

class Bar:

    def __init__(self, bar):
        """
        :type bar: str
        """
        print bar

class Foo:
    """
    :type my_class: Bar.__class__
    """

    def __init__(self, cinstance=Bar):
        """
        :type cinstance: Bar.__class__
        """
        self.my_class = cinstance

    def run(self):
        # it should print an unexpected type warning, but it doesn't.
        self.my_class(2)

If I just put Bar instead of Bar.__class__, of course PyCharm tell me that Bar cannot be call. So how to tell him that I'm giving him the class ?

Note that with the @classmethod decorator, PyCharm has no issue to understand we are speaking about the class and not the instance.

Here are my attempts :

Attempt with <code>Bar.__name__</code>

Attempt with <code>Bar.__class__</code>

Attempt with <code>Bar</code>

like image 266
FunkySayu Avatar asked Jul 10 '15 13:07

FunkySayu


1 Answers

The PyCharm support told me the following :

As PyCharm developer said: You cannot distinguish classes and instances in type hints. The name of a class in a type hint means that an instance of that class is expected. If your function accepts the class itself, your options are either not to use type hints at all or use the 'type' as a class name. Anyway, there won't be any useful code completion in these cases. See also https://youtrack.jetbrains.com/issue/PY-11615.

The only way to specificate an argument is a class is to use :type arg: type, but the completion won't work well. There is no other way currently.

like image 55
FunkySayu Avatar answered Oct 04 '22 02:10

FunkySayu