Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type hint for a class reference?

I am looking at PEP 484 and cannot find a description of how to type hint a class reference. Are class references declared as Callables as shown below?

from typing import Callable

class SomeClass:
    def __init__(self):
        self.s = 'Hello'

    def display(self):
        print(self.s)

x: Callable[[], SomeClass] = SomeClass

instance = x()
instance.display()
like image 316
Toaster Avatar asked Jul 22 '19 14:07

Toaster


People also ask

What is type hint?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.

How do you write a class hint in Python?

In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).

What is type class in Python?

type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass. In the above case: x is an instance of class Foo . Foo is an instance of the type metaclass.

Should I use type hinting in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.


1 Answers

If you only care that x is a class, you would just use type (or some other appropriate metaclass).

x: type = SomeClass

If x should be SomeClass or one of its descendants, use typing.Type

x: typing.Type[SomeClass] = SomeClass

If x has to be exactly SomeClass (for whatever reason), I think typing.TypeVar is the appropriate choice.

x: typing.TypeVar('SomeClass', SomeClass) = SomeClass
like image 56
chepner Avatar answered Sep 25 '22 12:09

chepner