How to annotate a type that's a class object (instead of a class instance)?

前端 未结 1 927
走了就别回头了
走了就别回头了 2020-12-10 23:56

What is the proper way to annotate a function argument that expects a class object instead of an instance of that class?

In the example below, some_class

相关标签:
1条回答
  • 2020-12-11 00:36

    To annotate an object that is a class, use typing.Type. For example, this would tell the type checker that some_class is class Foo or any of its subclasses:

    from typing import Type
    class Foo: ...
    class Bar(Foo): ...
    class Baz: ...
    some_class: Type[Foo]
    some_class = Foo # ok
    some_class = Bar # ok
    some_class = Baz # error
    some_class = Foo() # error
    

    Note that Type[Union[Foo, Bar, Baz]] and Union[Type[Foo], Type[Bar], Type[Baz]] are completely equivalent.

    If some_class could be any of a number of classes, you may want to make them all inherit from the same base class, and use Type[BaseClass]. Note that the inheritance must be non-virtual for now (mypy support for virtual inheritance is being discussed).

    Edited to confirm that Type[Union[... is allowed.

    0 讨论(0)
提交回复
热议问题