Python 3.8 launched a neat new characteristic: protocols. Protocols are a substitute for abstract base classes (ABC), and permit structural subtyping — checking whether or not two courses are appropriate based mostly on accessible attributes and features alone. On this publish we’ll go into the main points about this and present tips on how to use protocols utilizing sensible examples.
Allow us to start by discussing how Python is typed. It’s a dynamically typed language, that means varieties are inferred at runtime and the next code runs with out issues:
def add(x, y):
return x + yprint(add(2, 3))
print(add("str1", "str2"))
The primary name leads to an integer addition returning 5, the second in a string concatenation returning “str1str2”. That is completely different to e.g. C++, which is statically typed — and we now have to supply sort declarations:
int add(int x, int y) {
return x + y;
}std::string add(std::string x, std::string y) {
return x + y;
}
int essential()
{
std::cout<<add(2, 3);
std::cout << add("str1", "str2");
return 0;
}
Static typing presents the benefit of getting the potential to catching errors at compile time — whereas in dynamically typed languages we solely encounter these throughout runtime. However, dynamic typing can permit faster prototyping and experimentation — one motive why Python has grow to be so standard.
Dynamic typing can also be known as duck typing, based mostly on the saying: “if it walks like a duck and it quacks like a duck, then it should be a duck”. Ergo: if objects provide the identical attributes / features, they need to be handled equally, and e.g. might be handed to features requiring the opposite sort.
However, particularly in bigger, extra skilled software program merchandise, this unreliability presents extra down- than upsides — and the pattern thus goes in the direction of static sort checking, e.g. through providing type hints with mypy.
Subtyping
One fascinating problem — hinted above e.g. within the brief paragraph about duck typing — is subtyping. If we now have a perform with signature foo(x: X)
, what different courses besides X
does mypy permit to be handed to the perform? (Word we now solely…