Python docstring type annotation - class, not instance?

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 do this:

 :type klass: A 

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

+6
source share
4 answers

According to pycharm docs as close as possible:

 () -> SomeClass 

So in your example

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

This means (for PyCharm) that the argument you provide is a function that returns an object of a certain type. It will correctly type prompts after creating an object.

+4
source

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

I note that PyCharm does not consider () -> A as a class; if you call a class A method based on this syntax, checking PyCharm will mean that it cannot find the reference class.

This is filed in bugtracker JetBrains , although it was closed based on earlier comments. Given Guido's recent comments in the first link, I hope JetBrains opens again.

+2
source

All classes are instances of the type class:

 >>> class Foo: ... pass ... >>> type(Foo()) <class '__main__.Foo'> >>> type(Foo) <class 'type'> >>> type(Foo) is type True 

So the correct answer is:

 :type klass: type 
0
source

Answer Type . If you have the typing module installed, you can also bind this class as a subclass of something, as in the following example:

 class BaseUser(): pass class Admin(BaseUser): pass class Staff(BaseUser): pass class Client(BaseUser): pass 

then

 from typing import Type, TypeVar U = TypeVar('U', bound=BaseUser) def new_user(user_class): """ type user_class: Type[U] """ return user_class() 

and the following are use

 new_user(Admin) new_user(Client) new_user(Staff) 

Picharm | IDEA understands typing hints well, so it will do the trick

0
source

Source: https://habr.com/ru/post/985192/


All Articles