In typing, you would often see following class definitions:
from typing import Protocol, runtime_checkable, TypeVar
T_covTypeVar(T_cov, covariantTrue)
runtime_checkable
class ProtocolClass(Protocol[T_cov]): ...
If it was written in
.pyi
file, we would even skip the
@runtime_checkable
decorator preceding the protocol class. That decorator
allows to transform protocol class to a runtime protocol, what subsequently allows to use this class in
isinstance()
and
issubclass()
functions. As since Python 3.12 you have new type notation, you can even skip initializing a new type parameter via
TypeVar
constructor, but to
keep accordance with older Python versions, it is still used so far. With protocol classes I would like to happily introduce the
protocol
keyword:
since 3.12
protocol <protocol-class-name>[[type-parameters]]([inherited-classes]): <protocol-class-body>
before 3.12
protocol <protocol-class-name>([inherited-classes]): <protocol-class-body>
Protocol classes are just like interfaces in TypeScript - their members have lack of body. Declarations equipped with preceding
protocol
keywords
are classes, and below is its
class
keyword syntax equivalent.
since 3.12
class <class-name>[[type-parameters]](Protocol[[type-parameters]], [inherited-classes]): <class-body>
before 3.12
class <class-name>(Protocol[[type-parameters]], [inherited-classes]): <class-body>
I know it won't be accepted, at least I tried.
Article written by Aveyzan on 26th August 2024, 10:01 AM according to time in Greenwich