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 :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With