Python Type Hinting: Duck Type Compatibility and Consistent-With
<p>Sometimes, Python type hinting can make things easier. True, not always — but at least in my opinion, quite often it does — given that it’s done wisely. Some disagree, but I am not going to dispute with them: in my eyes, this is quite a subjective subject.</p>
<p>I wrote what I think about Python type hinting, how to use it to increase code readability, and how <em>not</em> to use it to do otherwise, in the following article:</p>
<h2><a href="https://betterprogramming.pub/pythons-type-hinting-friend-foe-or-just-a-headache-73c7849039c7?source=post_page-----72e8b348d8ac--------------------------------" rel="noopener ugc nofollow" target="_blank">Python’s Type Hinting: Friend, Foe, or Just a Headache?</a></h2>
<h3><a href="https://betterprogramming.pub/pythons-type-hinting-friend-foe-or-just-a-headache-73c7849039c7?source=post_page-----72e8b348d8ac--------------------------------" rel="noopener ugc nofollow" target="_blank">Type hinting’s popularity is increasing in the Python community. Where will this lead us? What can we do to use it…</a></h3>
<p><a href="https://betterprogramming.pub/pythons-type-hinting-friend-foe-or-just-a-headache-73c7849039c7?source=post_page-----72e8b348d8ac--------------------------------" rel="noopener ugc nofollow" target="_blank">betterprogramming.pub</a></p>
<p>Today, we’ll discuss what <em>consistent-with</em> and <em>duck-type compatibility </em>mean in terms of Python types.</p>
<p>Imagine you’re hinting the use of <code>float</code>, like in the function below:</p>
<pre>
from collections.abc import Sequence
def sum_of_squares(x: Sequence[float]) -> float:
n, s = len(x), sum(x)
return sum((x_i - s/n)**2 for x_i in x)</pre>
<p>This is a typical statistical function, calculating the sum of squares of a variable. It takes a container of floating-point numbers and returns a float.</p>
<p>As you see, to annotate the function, I used <code>Sequence</code>, a generic abstract base class available from <code>collections.abc</code> (before Python 3.9 you needed to use <code>typing.Sequence</code>). This means you can provide a list or a tuple — but you can’t provide, for instance, a generator¹.</p>
<p><a href="https://towardsdatascience.com/python-type-hinting-duck-type-compatibility-and-consistent-with-72e8b348d8ac">Click Here</a></p>