How to specify class or function type in docstring for PyCharm parser
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.
For functions, specifying using callable
works with PyCharm.
If you want to specify that a parameter is of type SomeClass
, it should be declared as such:
@type (param): SomeClass
Specified properly, you should get something like this:
If you don't specify the type of the parameter properly:
At this point, I figured I would dig a little deeper to see if I could find anything interesting. If you go to the declaration of an object's .__class__
, you'll be directed here (in builtins.py
):
Perhaps __class__
was set to None
? Even if it is by default but then updated when the class gets instantiated (which would be my guess as to what happens), this might be what PyCharm infers __class__
resolves to. All of this is just speculation on my end and may as well be incorrect, but... Just for the heck of it, what behavior can we see if we set a parameter's type to None
, then?
Looks like the same thing that happened when we set the type to SomeClass.__fake__
(and I tested it with SomeClass.__class__
, and the same thing happens there too.)
So I suppose the question at hand is, why can't you use @type cinstance: Bar
?