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()
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.
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 ).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With