Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python docstring type annotation -- a class, not an instance?

Tags:

python

pycharm

Let's say I have:

class A(object):
   pass

class B(A):
   pass

I want to declare a function that takes a subclass of A as an argument:

def do_something(klass):
   """
   :type klass: WHAT_HERE
   """
   pass

What should I put in WHAT_HERE? If I make this:

:type klass: A

PyCharm thinks that I should give an instance of A as an argument, not the class itself.

like image 277
Matt Avatar asked Apr 15 '15 15:04

Matt


2 Answers

According to the pycharm docs as close as you can get is:

() -> SomeClass

So in your example

def do_something(klass):
   """
   :type klass: () -> A
   """
   pass

This means (for PyCharm) that the argument you are providing is a function that returns an object of a given type. It will properly type hint anything after the object creation.

like image 137
aseeon Avatar answered Nov 01 '22 08:11

aseeon


Guido answered this question here, but I believe PyCharm does not correctly support the appropriate syntax in Python 2. I believe the syntax should be (...) -> A in PyCharm with Python 2. In Python 3, the appropriate syntax is Callable[..., A].

I note that PyCharm doesn't treat () -> A as a class either; if you call a classmethod on A using this syntax, PyCharm inspection will flag that it can't find the referenced classmethod.

This has been filed in the JetBrains bugtracker, though was closed based on earlier comments. Given Guido's recent comments in the first reference, I'm hoping JetBrains will reopen.

like image 3
Malina Avatar answered Nov 01 '22 06:11

Malina