Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc
<p>What's the difference of using <code>List</code>, <code>Tuple</code>, etc. from <code>typing</code> module:</p>

<pre><code>from typing import Tuple

def f(points: Tuple):
    return map(do_stuff, points)
</code></pre>

<p>As opposed to referring to Python's types directly:</p>

<pre><code>def f(points: tuple):
    return map(do_stuff, points)
</code></pre>

<p>And when should I use one over the other?</p>

<p><code>typing.Tuple</code> and <code>typing.List</code> are <a href="https://docs.python.org/3/library/typing.html#generics" rel="nofollow"><em>Generic types</em></a>; this means you can specify what type their <em>contents</em> must be:</p>

<pre><code>def f(points: Tuple[float, float]):
    return map(do_stuff, points)
</code></pre>

<p>This specifies that the tuple passed in must contain two <code>float</code> values. You can't do this with the built-in <code>tuple</code> type.</p>

<p><a href="https://docs.python.org/3/library/typing.html#typing.Tuple" rel="nofollow"><code>typing.Tuple</code></a> is special here in that it lets you specify a specific number of elements expected and the type of each position. Use ellipsis if the length is not set and the type should be repeated: <code>Tuple[float, ...]</code> describes a variable-length <code>tuple</code> with <code>float</code>s.</p>

<p>For <a href="https://docs.python.org/3/library/typing.html#typing.List" rel="nofollow"><code>typing.List</code></a> and other sequence types you generally only specify the type for all elements; <code>List[str]</code> is a list of strings, of any size. Note that functions should preferentially take <a href="https://docs.python.org/3/library/typing.html#typing.Sequence" rel="nofollow"><code>type.Sequence</code></a> as arguments and <code>typing.List</code> is typically only used for return types; generally speaking most functions would take any sequence and only iterate, but when you return a <code>list</code>, you really are returning a specific, mutable sequence type.</p>

<p>You should always pick the <code>typing</code> generics even when you are not currently restricting the contents. It is easier to add that constraint later with a generic type as the resulting change will be smaller. </p>

python python-3.5 typing type-hinting