Python Type Hinting: Duck Type Compatibility and Consistent-With

<p>Sometimes, Python type hinting can make things easier. True, not always &mdash; but at least in my opinion, quite often it does &mdash; given that it&rsquo;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&nbsp;<em>not</em>&nbsp;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&rsquo;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&rsquo;s popularity is increasing in the Python community. Where will this lead us? What can we do to use it&hellip;</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&rsquo;ll discuss what&nbsp;<em>consistent-with</em>&nbsp;and&nbsp;<em>duck-type compatibility&nbsp;</em>mean in terms of Python types.</p> <p>Imagine you&rsquo;re hinting the use of&nbsp;<code>float</code>, like in the function below:</p> <pre> from collections.abc import Sequence def sum_of_squares(x: Sequence[float]) -&gt; 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&nbsp;<code>Sequence</code>, a generic abstract base class available from&nbsp;<code>collections.abc</code>&nbsp;(before Python 3.9 you needed to use&nbsp;<code>typing.Sequence</code>). This means you can provide a list or a tuple &mdash; but you can&rsquo;t provide, for instance, a generator&sup1;.</p> <p><a href="https://towardsdatascience.com/python-type-hinting-duck-type-compatibility-and-consistent-with-72e8b348d8ac">Click Here</a></p>