1453 lines
141 KiB
HTML
1453 lines
141 KiB
HTML
|
||
<!DOCTYPE html>
|
||
|
||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>typing — Support for type hints — Python 3.7.4 documentation</title>
|
||
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
|
||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
|
||
|
||
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
|
||
<script type="text/javascript" src="../_static/jquery.js"></script>
|
||
<script type="text/javascript" src="../_static/underscore.js"></script>
|
||
<script type="text/javascript" src="../_static/doctools.js"></script>
|
||
<script type="text/javascript" src="../_static/language_data.js"></script>
|
||
|
||
<script type="text/javascript" src="../_static/sidebar.js"></script>
|
||
|
||
<link rel="search" type="application/opensearchdescription+xml"
|
||
title="Search within Python 3.7.4 documentation"
|
||
href="../_static/opensearch.xml"/>
|
||
<link rel="author" title="About these documents" href="../about.html" />
|
||
<link rel="index" title="Index" href="../genindex.html" />
|
||
<link rel="search" title="Search" href="../search.html" />
|
||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||
<link rel="next" title="pydoc — Documentation generator and online help system" href="pydoc.html" />
|
||
<link rel="prev" title="Development Tools" href="development.html" />
|
||
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
|
||
<link rel="canonical" href="https://docs.python.org/3/library/typing.html" />
|
||
|
||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||
<script type="text/javascript" src="../_static/switchers.js"></script>
|
||
|
||
|
||
|
||
<style>
|
||
@media only screen {
|
||
table.full-width-table {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
|
||
|
||
</head><body>
|
||
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>Navigation</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="General Index"
|
||
accesskey="I">index</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python Module Index"
|
||
>modules</a> |</li>
|
||
<li class="right" >
|
||
<a href="pydoc.html" title="pydoc — Documentation generator and online help system"
|
||
accesskey="N">next</a> |</li>
|
||
<li class="right" >
|
||
<a href="development.html" title="Development Tools"
|
||
accesskey="P">previous</a> |</li>
|
||
<li><img src="../_static/py.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
|
||
<li class="nav-item nav-item-2"><a href="development.html" accesskey="U">Development Tools</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
|
||
<div class="document">
|
||
<div class="documentwrapper">
|
||
<div class="bodywrapper">
|
||
<div class="body" role="main">
|
||
|
||
<div class="section" id="module-typing">
|
||
<span id="typing-support-for-type-hints"></span><h1><a class="reference internal" href="#module-typing" title="typing: Support for type hints (see PEP 484)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">typing</span></code></a> — Support for type hints<a class="headerlink" href="#module-typing" title="Permalink to this headline">¶</a></h1>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.</span></p>
|
||
</div>
|
||
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/typing.py">Lib/typing.py</a></p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>The typing module has been included in the standard library on a
|
||
<a class="reference internal" href="../glossary.html#term-provisional-api"><span class="xref std std-term">provisional basis</span></a>. New features might
|
||
be added and API may change even between minor releases if deemed
|
||
necessary by the core developers.</p>
|
||
</div>
|
||
<hr class="docutils" />
|
||
<p>This module supports type hints as specified by <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> and <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a>.
|
||
The most fundamental support consists of the types <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>, <a class="reference internal" href="#typing.Union" title="typing.Union"><code class="xref py py-data docutils literal notranslate"><span class="pre">Union</span></code></a>,
|
||
<a class="reference internal" href="#typing.Tuple" title="typing.Tuple"><code class="xref py py-data docutils literal notranslate"><span class="pre">Tuple</span></code></a>, <a class="reference internal" href="#typing.Callable" title="typing.Callable"><code class="xref py py-data docutils literal notranslate"><span class="pre">Callable</span></code></a>, <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypeVar</span></code></a>, and
|
||
<a class="reference internal" href="#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generic</span></code></a>. For full specification please see <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a>. For
|
||
a simplified introduction to type hints see <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0483"><strong>PEP 483</strong></a>.</p>
|
||
<p>The function below takes and returns a string and is annotated as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">greeting</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="s1">'Hello '</span> <span class="o">+</span> <span class="n">name</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In the function <code class="docutils literal notranslate"><span class="pre">greeting</span></code>, the argument <code class="docutils literal notranslate"><span class="pre">name</span></code> is expected to be of type
|
||
<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and the return type <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>. Subtypes are accepted as
|
||
arguments.</p>
|
||
<div class="section" id="type-aliases">
|
||
<h2>Type aliases<a class="headerlink" href="#type-aliases" title="Permalink to this headline">¶</a></h2>
|
||
<p>A type alias is defined by assigning the type to the alias. In this example,
|
||
<code class="docutils literal notranslate"><span class="pre">Vector</span></code> and <code class="docutils literal notranslate"><span class="pre">List[float]</span></code> will be treated as interchangeable synonyms:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">List</span>
|
||
<span class="n">Vector</span> <span class="o">=</span> <span class="n">List</span><span class="p">[</span><span class="nb">float</span><span class="p">]</span>
|
||
|
||
<span class="k">def</span> <span class="nf">scale</span><span class="p">(</span><span class="n">scalar</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span> <span class="n">vector</span><span class="p">:</span> <span class="n">Vector</span><span class="p">)</span> <span class="o">-></span> <span class="n">Vector</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="p">[</span><span class="n">scalar</span> <span class="o">*</span> <span class="n">num</span> <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">vector</span><span class="p">]</span>
|
||
|
||
<span class="c1"># typechecks; a list of floats qualifies as a Vector.</span>
|
||
<span class="n">new_vector</span> <span class="o">=</span> <span class="n">scale</span><span class="p">(</span><span class="mf">2.0</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">4.2</span><span class="p">,</span> <span class="mf">5.4</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Type aliases are useful for simplifying complex type signatures. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Dict</span><span class="p">,</span> <span class="n">Tuple</span><span class="p">,</span> <span class="n">Sequence</span>
|
||
|
||
<span class="n">ConnectionOptions</span> <span class="o">=</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">]</span>
|
||
<span class="n">Address</span> <span class="o">=</span> <span class="n">Tuple</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">]</span>
|
||
<span class="n">Server</span> <span class="o">=</span> <span class="n">Tuple</span><span class="p">[</span><span class="n">Address</span><span class="p">,</span> <span class="n">ConnectionOptions</span><span class="p">]</span>
|
||
|
||
<span class="k">def</span> <span class="nf">broadcast_message</span><span class="p">(</span><span class="n">message</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">servers</span><span class="p">:</span> <span class="n">Sequence</span><span class="p">[</span><span class="n">Server</span><span class="p">])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="c1"># The static type checker will treat the previous type signature as</span>
|
||
<span class="c1"># being exactly equivalent to this one.</span>
|
||
<span class="k">def</span> <span class="nf">broadcast_message</span><span class="p">(</span>
|
||
<span class="n">message</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span>
|
||
<span class="n">servers</span><span class="p">:</span> <span class="n">Sequence</span><span class="p">[</span><span class="n">Tuple</span><span class="p">[</span><span class="n">Tuple</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">],</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">]]])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that <code class="docutils literal notranslate"><span class="pre">None</span></code> as a type hint is a special case and is replaced by
|
||
<code class="docutils literal notranslate"><span class="pre">type(None)</span></code>.</p>
|
||
</div>
|
||
<div class="section" id="newtype">
|
||
<span id="distinct"></span><h2>NewType<a class="headerlink" href="#newtype" title="Permalink to this headline">¶</a></h2>
|
||
<p>Use the <a class="reference internal" href="#typing.NewType" title="typing.NewType"><code class="xref py py-func docutils literal notranslate"><span class="pre">NewType()</span></code></a> helper function to create distinct types:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">NewType</span>
|
||
|
||
<span class="n">UserId</span> <span class="o">=</span> <span class="n">NewType</span><span class="p">(</span><span class="s1">'UserId'</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span>
|
||
<span class="n">some_id</span> <span class="o">=</span> <span class="n">UserId</span><span class="p">(</span><span class="mi">524313</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The static type checker will treat the new type as if it were a subclass
|
||
of the original type. This is useful in helping catch logical errors:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_user_name</span><span class="p">(</span><span class="n">user_id</span><span class="p">:</span> <span class="n">UserId</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="c1"># typechecks</span>
|
||
<span class="n">user_a</span> <span class="o">=</span> <span class="n">get_user_name</span><span class="p">(</span><span class="n">UserId</span><span class="p">(</span><span class="mi">42351</span><span class="p">))</span>
|
||
|
||
<span class="c1"># does not typecheck; an int is not a UserId</span>
|
||
<span class="n">user_b</span> <span class="o">=</span> <span class="n">get_user_name</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>You may still perform all <code class="docutils literal notranslate"><span class="pre">int</span></code> operations on a variable of type <code class="docutils literal notranslate"><span class="pre">UserId</span></code>,
|
||
but the result will always be of type <code class="docutils literal notranslate"><span class="pre">int</span></code>. This lets you pass in a
|
||
<code class="docutils literal notranslate"><span class="pre">UserId</span></code> wherever an <code class="docutils literal notranslate"><span class="pre">int</span></code> might be expected, but will prevent you from
|
||
accidentally creating a <code class="docutils literal notranslate"><span class="pre">UserId</span></code> in an invalid way:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># 'output' is of type 'int', not 'UserId'</span>
|
||
<span class="n">output</span> <span class="o">=</span> <span class="n">UserId</span><span class="p">(</span><span class="mi">23413</span><span class="p">)</span> <span class="o">+</span> <span class="n">UserId</span><span class="p">(</span><span class="mi">54341</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that these checks are enforced only by the static type checker. At runtime
|
||
the statement <code class="docutils literal notranslate"><span class="pre">Derived</span> <span class="pre">=</span> <span class="pre">NewType('Derived',</span> <span class="pre">Base)</span></code> will make <code class="docutils literal notranslate"><span class="pre">Derived</span></code> a
|
||
function that immediately returns whatever parameter you pass it. That means
|
||
the expression <code class="docutils literal notranslate"><span class="pre">Derived(some_value)</span></code> does not create a new class or introduce
|
||
any overhead beyond that of a regular function call.</p>
|
||
<p>More precisely, the expression <code class="docutils literal notranslate"><span class="pre">some_value</span> <span class="pre">is</span> <span class="pre">Derived(some_value)</span></code> is always
|
||
true at runtime.</p>
|
||
<p>This also means that it is not possible to create a subtype of <code class="docutils literal notranslate"><span class="pre">Derived</span></code>
|
||
since it is an identity function at runtime, not an actual type:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">NewType</span>
|
||
|
||
<span class="n">UserId</span> <span class="o">=</span> <span class="n">NewType</span><span class="p">(</span><span class="s1">'UserId'</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span>
|
||
|
||
<span class="c1"># Fails at runtime and does not typecheck</span>
|
||
<span class="k">class</span> <span class="nc">AdminUserId</span><span class="p">(</span><span class="n">UserId</span><span class="p">):</span> <span class="k">pass</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>However, it is possible to create a <a class="reference internal" href="#typing.NewType" title="typing.NewType"><code class="xref py py-func docutils literal notranslate"><span class="pre">NewType()</span></code></a> based on a ‘derived’ <code class="docutils literal notranslate"><span class="pre">NewType</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">NewType</span>
|
||
|
||
<span class="n">UserId</span> <span class="o">=</span> <span class="n">NewType</span><span class="p">(</span><span class="s1">'UserId'</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span>
|
||
|
||
<span class="n">ProUserId</span> <span class="o">=</span> <span class="n">NewType</span><span class="p">(</span><span class="s1">'ProUserId'</span><span class="p">,</span> <span class="n">UserId</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>and typechecking for <code class="docutils literal notranslate"><span class="pre">ProUserId</span></code> will work as expected.</p>
|
||
<p>See <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> for more details.</p>
|
||
<div class="admonition note">
|
||
<p class="admonition-title">Note</p>
|
||
<p>Recall that the use of a type alias declares two types to be <em>equivalent</em> to
|
||
one another. Doing <code class="docutils literal notranslate"><span class="pre">Alias</span> <span class="pre">=</span> <span class="pre">Original</span></code> will make the static type checker
|
||
treat <code class="docutils literal notranslate"><span class="pre">Alias</span></code> as being <em>exactly equivalent</em> to <code class="docutils literal notranslate"><span class="pre">Original</span></code> in all cases.
|
||
This is useful when you want to simplify complex type signatures.</p>
|
||
<p>In contrast, <code class="docutils literal notranslate"><span class="pre">NewType</span></code> declares one type to be a <em>subtype</em> of another.
|
||
Doing <code class="docutils literal notranslate"><span class="pre">Derived</span> <span class="pre">=</span> <span class="pre">NewType('Derived',</span> <span class="pre">Original)</span></code> will make the static type
|
||
checker treat <code class="docutils literal notranslate"><span class="pre">Derived</span></code> as a <em>subclass</em> of <code class="docutils literal notranslate"><span class="pre">Original</span></code>, which means a
|
||
value of type <code class="docutils literal notranslate"><span class="pre">Original</span></code> cannot be used in places where a value of type
|
||
<code class="docutils literal notranslate"><span class="pre">Derived</span></code> is expected. This is useful when you want to prevent logic
|
||
errors with minimal runtime cost.</p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="callable">
|
||
<h2>Callable<a class="headerlink" href="#callable" title="Permalink to this headline">¶</a></h2>
|
||
<p>Frameworks expecting callback functions of specific signatures might be
|
||
type hinted using <code class="docutils literal notranslate"><span class="pre">Callable[[Arg1Type,</span> <span class="pre">Arg2Type],</span> <span class="pre">ReturnType]</span></code>.</p>
|
||
<p>For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Callable</span>
|
||
|
||
<span class="k">def</span> <span class="nf">feeder</span><span class="p">(</span><span class="n">get_next_item</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[[],</span> <span class="nb">str</span><span class="p">])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="c1"># Body</span>
|
||
|
||
<span class="k">def</span> <span class="nf">async_query</span><span class="p">(</span><span class="n">on_success</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[[</span><span class="nb">int</span><span class="p">],</span> <span class="kc">None</span><span class="p">],</span>
|
||
<span class="n">on_error</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[[</span><span class="nb">int</span><span class="p">,</span> <span class="ne">Exception</span><span class="p">],</span> <span class="kc">None</span><span class="p">])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="c1"># Body</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>It is possible to declare the return type of a callable without specifying
|
||
the call signature by substituting a literal ellipsis
|
||
for the list of arguments in the type hint: <code class="docutils literal notranslate"><span class="pre">Callable[...,</span> <span class="pre">ReturnType]</span></code>.</p>
|
||
</div>
|
||
<div class="section" id="generics">
|
||
<span id="id1"></span><h2>Generics<a class="headerlink" href="#generics" title="Permalink to this headline">¶</a></h2>
|
||
<p>Since type information about objects kept in containers cannot be statically
|
||
inferred in a generic way, abstract base classes have been extended to support
|
||
subscription to denote expected types for container elements.</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Mapping</span><span class="p">,</span> <span class="n">Sequence</span>
|
||
|
||
<span class="k">def</span> <span class="nf">notify_by_email</span><span class="p">(</span><span class="n">employees</span><span class="p">:</span> <span class="n">Sequence</span><span class="p">[</span><span class="n">Employee</span><span class="p">],</span>
|
||
<span class="n">overrides</span><span class="p">:</span> <span class="n">Mapping</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Generics can be parameterized by using a new factory available in typing
|
||
called <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypeVar</span></code></a>.</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Sequence</span><span class="p">,</span> <span class="n">TypeVar</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span> <span class="c1"># Declare type variable</span>
|
||
|
||
<span class="k">def</span> <span class="nf">first</span><span class="p">(</span><span class="n">l</span><span class="p">:</span> <span class="n">Sequence</span><span class="p">[</span><span class="n">T</span><span class="p">])</span> <span class="o">-></span> <span class="n">T</span><span class="p">:</span> <span class="c1"># Generic function</span>
|
||
<span class="k">return</span> <span class="n">l</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</div>
|
||
<div class="section" id="user-defined-generic-types">
|
||
<h2>User-defined generic types<a class="headerlink" href="#user-defined-generic-types" title="Permalink to this headline">¶</a></h2>
|
||
<p>A user-defined class can be defined as a generic class.</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Generic</span>
|
||
<span class="kn">from</span> <span class="nn">logging</span> <span class="k">import</span> <span class="n">Logger</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span>
|
||
|
||
<span class="k">class</span> <span class="nc">LoggedVar</span><span class="p">(</span><span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">]):</span>
|
||
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">T</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">logger</span><span class="p">:</span> <span class="n">Logger</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">logger</span> <span class="o">=</span> <span class="n">logger</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
|
||
|
||
<span class="k">def</span> <span class="nf">set</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">new</span><span class="p">:</span> <span class="n">T</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="s1">'Set '</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">))</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">new</span>
|
||
|
||
<span class="k">def</span> <span class="nf">get</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-></span> <span class="n">T</span><span class="p">:</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="s1">'Get '</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">))</span>
|
||
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span>
|
||
|
||
<span class="k">def</span> <span class="nf">log</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">'</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p><code class="docutils literal notranslate"><span class="pre">Generic[T]</span></code> as a base class defines that the class <code class="docutils literal notranslate"><span class="pre">LoggedVar</span></code> takes a
|
||
single type parameter <code class="docutils literal notranslate"><span class="pre">T</span></code> . This also makes <code class="docutils literal notranslate"><span class="pre">T</span></code> valid as a type within the
|
||
class body.</p>
|
||
<p>The <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generic</span></code></a> base class uses a metaclass that defines
|
||
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> so that <code class="docutils literal notranslate"><span class="pre">LoggedVar[t]</span></code> is valid as a type:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Iterable</span>
|
||
|
||
<span class="k">def</span> <span class="nf">zero_all_vars</span><span class="p">(</span><span class="nb">vars</span><span class="p">:</span> <span class="n">Iterable</span><span class="p">[</span><span class="n">LoggedVar</span><span class="p">[</span><span class="nb">int</span><span class="p">]])</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">:</span>
|
||
<span class="n">var</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>A generic type can have any number of type variables, and type variables may
|
||
be constrained:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Generic</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span>
|
||
<span class="n">S</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'S'</span><span class="p">,</span> <span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
|
||
|
||
<span class="k">class</span> <span class="nc">StrangePair</span><span class="p">(</span><span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">,</span> <span class="n">S</span><span class="p">]):</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Each type variable argument to <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generic</span></code></a> must be distinct.
|
||
This is thus invalid:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Generic</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span>
|
||
|
||
<span class="k">class</span> <span class="nc">Pair</span><span class="p">(</span><span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">,</span> <span class="n">T</span><span class="p">]):</span> <span class="c1"># INVALID</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>You can use multiple inheritance with <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generic</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Generic</span><span class="p">,</span> <span class="n">Sized</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span>
|
||
|
||
<span class="k">class</span> <span class="nc">LinkedList</span><span class="p">(</span><span class="n">Sized</span><span class="p">,</span> <span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">]):</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When inheriting from generic classes, some type variables could be fixed:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Mapping</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span>
|
||
|
||
<span class="k">class</span> <span class="nc">MyDict</span><span class="p">(</span><span class="n">Mapping</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">T</span><span class="p">]):</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In this case <code class="docutils literal notranslate"><span class="pre">MyDict</span></code> has a single parameter, <code class="docutils literal notranslate"><span class="pre">T</span></code>.</p>
|
||
<p>Using a generic class without specifying type parameters assumes
|
||
<a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> for each position. In the following example, <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> is
|
||
not generic but implicitly inherits from <code class="docutils literal notranslate"><span class="pre">Iterable[Any]</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Iterable</span>
|
||
|
||
<span class="k">class</span> <span class="nc">MyIterable</span><span class="p">(</span><span class="n">Iterable</span><span class="p">):</span> <span class="c1"># Same as Iterable[Any]</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>User defined generic type aliases are also supported. Examples:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">TypeVar</span><span class="p">,</span> <span class="n">Iterable</span><span class="p">,</span> <span class="n">Tuple</span><span class="p">,</span> <span class="n">Union</span>
|
||
<span class="n">S</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'S'</span><span class="p">)</span>
|
||
<span class="n">Response</span> <span class="o">=</span> <span class="n">Union</span><span class="p">[</span><span class="n">Iterable</span><span class="p">[</span><span class="n">S</span><span class="p">],</span> <span class="nb">int</span><span class="p">]</span>
|
||
|
||
<span class="c1"># Return type here is same as Union[Iterable[str], int]</span>
|
||
<span class="k">def</span> <span class="nf">response</span><span class="p">(</span><span class="n">query</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="n">Response</span><span class="p">[</span><span class="nb">str</span><span class="p">]:</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">,</span> <span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">,</span> <span class="nb">complex</span><span class="p">)</span>
|
||
<span class="n">Vec</span> <span class="o">=</span> <span class="n">Iterable</span><span class="p">[</span><span class="n">Tuple</span><span class="p">[</span><span class="n">T</span><span class="p">,</span> <span class="n">T</span><span class="p">]]</span>
|
||
|
||
<span class="k">def</span> <span class="nf">inproduct</span><span class="p">(</span><span class="n">v</span><span class="p">:</span> <span class="n">Vec</span><span class="p">[</span><span class="n">T</span><span class="p">])</span> <span class="o">-></span> <span class="n">T</span><span class="p">:</span> <span class="c1"># Same as Iterable[Tuple[T, T]]</span>
|
||
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">v</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The metaclass used by <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generic</span></code></a> is a subclass of <a class="reference internal" href="abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code></a>.
|
||
A generic class can be an ABC by including abstract methods or properties,
|
||
and generic classes can also have ABCs as base classes without a metaclass
|
||
conflict. Generic metaclasses are not supported. The outcome of parameterizing
|
||
generics is cached, and most types in the typing module are hashable and
|
||
comparable for equality.</p>
|
||
</div>
|
||
<div class="section" id="the-any-type">
|
||
<h2>The <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> type<a class="headerlink" href="#the-any-type" title="Permalink to this headline">¶</a></h2>
|
||
<p>A special kind of type is <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>. A static type checker will treat
|
||
every type as being compatible with <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> and <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> as being
|
||
compatible with every type.</p>
|
||
<p>This means that it is possible to perform any operation or method call on a
|
||
value of type on <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> and assign it to any variable:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">Any</span>
|
||
|
||
<span class="n">a</span> <span class="o">=</span> <span class="kc">None</span> <span class="c1"># type: Any</span>
|
||
<span class="n">a</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1"># OK</span>
|
||
<span class="n">a</span> <span class="o">=</span> <span class="mi">2</span> <span class="c1"># OK</span>
|
||
|
||
<span class="n">s</span> <span class="o">=</span> <span class="s1">''</span> <span class="c1"># type: str</span>
|
||
<span class="n">s</span> <span class="o">=</span> <span class="n">a</span> <span class="c1"># OK</span>
|
||
|
||
<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">item</span><span class="p">:</span> <span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
|
||
<span class="c1"># Typechecks; 'item' could be any type,</span>
|
||
<span class="c1"># and that type might have a 'bar' method</span>
|
||
<span class="n">item</span><span class="o">.</span><span class="n">bar</span><span class="p">()</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Notice that no typechecking is performed when assigning a value of type
|
||
<a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> to a more precise type. For example, the static type checker did
|
||
not report an error when assigning <code class="docutils literal notranslate"><span class="pre">a</span></code> to <code class="docutils literal notranslate"><span class="pre">s</span></code> even though <code class="docutils literal notranslate"><span class="pre">s</span></code> was
|
||
declared to be of type <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and receives an <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> value at
|
||
runtime!</p>
|
||
<p>Furthermore, all functions without a return type or parameter types will
|
||
implicitly default to using <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">legacy_parser</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
|
||
<span class="o">...</span>
|
||
<span class="k">return</span> <span class="n">data</span>
|
||
|
||
<span class="c1"># A static type checker will treat the above</span>
|
||
<span class="c1"># as having the same signature as:</span>
|
||
<span class="k">def</span> <span class="nf">legacy_parser</span><span class="p">(</span><span class="n">text</span><span class="p">:</span> <span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="n">Any</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
<span class="k">return</span> <span class="n">data</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This behavior allows <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> to be used as an <em>escape hatch</em> when you
|
||
need to mix dynamically and statically typed code.</p>
|
||
<p>Contrast the behavior of <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> with the behavior of <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.
|
||
Similar to <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>, every type is a subtype of <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>. However,
|
||
unlike <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>, the reverse is not true: <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> is <em>not</em> a
|
||
subtype of every other type.</p>
|
||
<p>That means when the type of a value is <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, a type checker will
|
||
reject almost all operations on it, and assigning it to a variable (or using
|
||
it as a return value) of a more specialized type is a type error. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">hash_a</span><span class="p">(</span><span class="n">item</span><span class="p">:</span> <span class="nb">object</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
|
||
<span class="c1"># Fails; an object does not have a 'magic' method.</span>
|
||
<span class="n">item</span><span class="o">.</span><span class="n">magic</span><span class="p">()</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="k">def</span> <span class="nf">hash_b</span><span class="p">(</span><span class="n">item</span><span class="p">:</span> <span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
|
||
<span class="c1"># Typechecks</span>
|
||
<span class="n">item</span><span class="o">.</span><span class="n">magic</span><span class="p">()</span>
|
||
<span class="o">...</span>
|
||
|
||
<span class="c1"># Typechecks, since ints and strs are subclasses of object</span>
|
||
<span class="n">hash_a</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
|
||
<span class="n">hash_a</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">)</span>
|
||
|
||
<span class="c1"># Typechecks, since Any is compatible with all types</span>
|
||
<span class="n">hash_b</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
|
||
<span class="n">hash_b</span><span class="p">(</span><span class="s2">"foo"</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Use <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> to indicate that a value could be any type in a typesafe
|
||
manner. Use <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> to indicate that a value is dynamically typed.</p>
|
||
</div>
|
||
<div class="section" id="classes-functions-and-decorators">
|
||
<h2>Classes, functions, and decorators<a class="headerlink" href="#classes-functions-and-decorators" title="Permalink to this headline">¶</a></h2>
|
||
<p>The module defines the following classes, functions and decorators:</p>
|
||
<dl class="class">
|
||
<dt id="typing.TypeVar">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">TypeVar</code><a class="headerlink" href="#typing.TypeVar" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Type variable.</p>
|
||
<p>Usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">)</span> <span class="c1"># Can be anything</span>
|
||
<span class="n">A</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="nb">str</span><span class="p">,</span> <span class="nb">bytes</span><span class="p">)</span> <span class="c1"># Must be str or bytes</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Type variables exist primarily for the benefit of static type
|
||
checkers. They serve as the parameters for generic types as well
|
||
as for generic function definitions. See class Generic for more
|
||
information on generic types. Generic functions work as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">repeat</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="n">T</span><span class="p">,</span> <span class="n">n</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">Sequence</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
|
||
<span class="sd">"""Return a list containing n references to x."""</span>
|
||
<span class="k">return</span> <span class="p">[</span><span class="n">x</span><span class="p">]</span><span class="o">*</span><span class="n">n</span>
|
||
|
||
<span class="k">def</span> <span class="nf">longest</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="n">A</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">A</span><span class="p">)</span> <span class="o">-></span> <span class="n">A</span><span class="p">:</span>
|
||
<span class="sd">"""Return the longest of two strings."""</span>
|
||
<span class="k">return</span> <span class="n">x</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">>=</span> <span class="nb">len</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="k">else</span> <span class="n">y</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The latter example’s signature is essentially the overloading
|
||
of <code class="docutils literal notranslate"><span class="pre">(str,</span> <span class="pre">str)</span> <span class="pre">-></span> <span class="pre">str</span></code> and <code class="docutils literal notranslate"><span class="pre">(bytes,</span> <span class="pre">bytes)</span> <span class="pre">-></span> <span class="pre">bytes</span></code>. Also note
|
||
that if the arguments are instances of some subclass of <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>,
|
||
the return type is still plain <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
|
||
<p>At runtime, <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">T)</span></code> will raise <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. In general,
|
||
<a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> should not be used with types.</p>
|
||
<p>Type variables may be marked covariant or contravariant by passing
|
||
<code class="docutils literal notranslate"><span class="pre">covariant=True</span></code> or <code class="docutils literal notranslate"><span class="pre">contravariant=True</span></code>. See <span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> for more
|
||
details. By default type variables are invariant. Alternatively,
|
||
a type variable may specify an upper bound using <code class="docutils literal notranslate"><span class="pre">bound=<type></span></code>.
|
||
This means that an actual type substituted (explicitly or implicitly)
|
||
for the type variable must be a subclass of the boundary type,
|
||
see <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Generic">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Generic</code><a class="headerlink" href="#typing.Generic" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Abstract base class for generic types.</p>
|
||
<p>A generic type is typically declared by inheriting from an
|
||
instantiation of this class with one or more type variables.
|
||
For example, a generic mapping type might be defined as:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mapping</span><span class="p">(</span><span class="n">Generic</span><span class="p">[</span><span class="n">KT</span><span class="p">,</span> <span class="n">VT</span><span class="p">]):</span>
|
||
<span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">:</span> <span class="n">KT</span><span class="p">)</span> <span class="o">-></span> <span class="n">VT</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
<span class="c1"># Etc.</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This class can then be used as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">X</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'X'</span><span class="p">)</span>
|
||
<span class="n">Y</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'Y'</span><span class="p">)</span>
|
||
|
||
<span class="k">def</span> <span class="nf">lookup_name</span><span class="p">(</span><span class="n">mapping</span><span class="p">:</span> <span class="n">Mapping</span><span class="p">[</span><span class="n">X</span><span class="p">,</span> <span class="n">Y</span><span class="p">],</span> <span class="n">key</span><span class="p">:</span> <span class="n">X</span><span class="p">,</span> <span class="n">default</span><span class="p">:</span> <span class="n">Y</span><span class="p">)</span> <span class="o">-></span> <span class="n">Y</span><span class="p">:</span>
|
||
<span class="k">try</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">mapping</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
|
||
<span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">default</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Type">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Type</code><span class="sig-paren">(</span><em>Generic[CT_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Type" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A variable annotated with <code class="docutils literal notranslate"><span class="pre">C</span></code> may accept a value of type <code class="docutils literal notranslate"><span class="pre">C</span></code>. In
|
||
contrast, a variable annotated with <code class="docutils literal notranslate"><span class="pre">Type[C]</span></code> may accept values that are
|
||
classes themselves – specifically, it will accept the <em>class object</em> of
|
||
<code class="docutils literal notranslate"><span class="pre">C</span></code>. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="mi">3</span> <span class="c1"># Has type 'int'</span>
|
||
<span class="n">b</span> <span class="o">=</span> <span class="nb">int</span> <span class="c1"># Has type 'Type[int]'</span>
|
||
<span class="n">c</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="c1"># Also has type 'Type[int]'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that <code class="docutils literal notranslate"><span class="pre">Type[C]</span></code> is covariant:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">User</span><span class="p">:</span> <span class="o">...</span>
|
||
<span class="k">class</span> <span class="nc">BasicUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">class</span> <span class="nc">ProUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">class</span> <span class="nc">TeamUser</span><span class="p">(</span><span class="n">User</span><span class="p">):</span> <span class="o">...</span>
|
||
|
||
<span class="c1"># Accepts User, BasicUser, ProUser, TeamUser, ...</span>
|
||
<span class="k">def</span> <span class="nf">make_new_user</span><span class="p">(</span><span class="n">user_class</span><span class="p">:</span> <span class="n">Type</span><span class="p">[</span><span class="n">User</span><span class="p">])</span> <span class="o">-></span> <span class="n">User</span><span class="p">:</span>
|
||
<span class="c1"># ...</span>
|
||
<span class="k">return</span> <span class="n">user_class</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The fact that <code class="docutils literal notranslate"><span class="pre">Type[C]</span></code> is covariant implies that all subclasses of
|
||
<code class="docutils literal notranslate"><span class="pre">C</span></code> should implement the same constructor signature and class method
|
||
signatures as <code class="docutils literal notranslate"><span class="pre">C</span></code>. The type checker should flag violations of this,
|
||
but should also allow constructor calls in subclasses that match the
|
||
constructor calls in the indicated base class. How the type checker is
|
||
required to handle this particular case may change in future revisions of
|
||
<span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a>.</p>
|
||
<p>The only legal parameters for <a class="reference internal" href="#typing.Type" title="typing.Type"><code class="xref py py-class docutils literal notranslate"><span class="pre">Type</span></code></a> are classes, <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>,
|
||
<a class="reference internal" href="#generics"><span class="std std-ref">type variables</span></a>, and unions of any of these types.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">new_non_team_user</span><span class="p">(</span><span class="n">user_class</span><span class="p">:</span> <span class="n">Type</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="n">BaseUser</span><span class="p">,</span> <span class="n">ProUser</span><span class="p">]]):</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p><code class="docutils literal notranslate"><span class="pre">Type[Any]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">Type</span></code> which in turn is equivalent
|
||
to <code class="docutils literal notranslate"><span class="pre">type</span></code>, which is the root of Python’s metaclass hierarchy.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Iterable">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Iterable</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Iterable" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Iterable" title="collections.abc.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Iterable</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Iterator">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Iterator</code><span class="sig-paren">(</span><em>Iterable[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Iterator" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Iterator" title="collections.abc.Iterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Iterator</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Reversible">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Reversible</code><span class="sig-paren">(</span><em>Iterable[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Reversible" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Reversible" title="collections.abc.Reversible"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Reversible</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsInt">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsInt</code><a class="headerlink" href="#typing.SupportsInt" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__int__</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsFloat">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsFloat</code><a class="headerlink" href="#typing.SupportsFloat" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__float__</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsComplex">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsComplex</code><a class="headerlink" href="#typing.SupportsComplex" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__complex__</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsBytes">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsBytes</code><a class="headerlink" href="#typing.SupportsBytes" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__bytes__</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsAbs">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsAbs</code><a class="headerlink" href="#typing.SupportsAbs" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__abs__</span></code> that is covariant
|
||
in its return type.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.SupportsRound">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">SupportsRound</code><a class="headerlink" href="#typing.SupportsRound" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An ABC with one abstract method <code class="docutils literal notranslate"><span class="pre">__round__</span></code>
|
||
that is covariant in its return type.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Container">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Container</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Container" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Container" title="collections.abc.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Container</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Hashable">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Hashable</code><a class="headerlink" href="#typing.Hashable" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An alias to <a class="reference internal" href="collections.abc.html#collections.abc.Hashable" title="collections.abc.Hashable"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Hashable</span></code></a></p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Sized">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Sized</code><a class="headerlink" href="#typing.Sized" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An alias to <a class="reference internal" href="collections.abc.html#collections.abc.Sized" title="collections.abc.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sized</span></code></a></p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Collection">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Collection</code><span class="sig-paren">(</span><em>Sized, Iterable[T_co], Container[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Collection" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Collection" title="collections.abc.Collection"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Collection</span></code></a></p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.0.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.AbstractSet">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">AbstractSet</code><span class="sig-paren">(</span><em>Sized, Collection[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.AbstractSet" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Set" title="collections.abc.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Set</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.MutableSet">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">MutableSet</code><span class="sig-paren">(</span><em>AbstractSet[T]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.MutableSet" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.MutableSet" title="collections.abc.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.MutableSet</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Mapping">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Mapping</code><span class="sig-paren">(</span><em>Sized, Collection[KT], Generic[VT_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Mapping" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Mapping</span></code></a>.
|
||
This type can be used as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_position_in_index</span><span class="p">(</span><span class="n">word_list</span><span class="p">:</span> <span class="n">Mapping</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">],</span> <span class="n">word</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">int</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">word_list</span><span class="p">[</span><span class="n">word</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.MutableMapping">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">MutableMapping</code><span class="sig-paren">(</span><em>Mapping[KT, VT]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.MutableMapping" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.MutableMapping</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Sequence">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Sequence</code><span class="sig-paren">(</span><em>Reversible[T_co], Collection[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Sequence" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.MutableSequence">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">MutableSequence</code><span class="sig-paren">(</span><em>Sequence[T]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.MutableSequence" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.MutableSequence" title="collections.abc.MutableSequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.MutableSequence</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ByteString">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ByteString</code><span class="sig-paren">(</span><em>Sequence[int]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.ByteString" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.ByteString" title="collections.abc.ByteString"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.ByteString</span></code></a>.</p>
|
||
<p>This type represents the types <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>,
|
||
and <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.</p>
|
||
<p>As a shorthand for this type, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> can be used to
|
||
annotate arguments of any of the types mentioned above.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Deque">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Deque</code><span class="sig-paren">(</span><em>deque, MutableSequence[T]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Deque" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.1.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.List">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">List</code><span class="sig-paren">(</span><em>list, MutableSequence[T]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.List" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Generic version of <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>.
|
||
Useful for annotating return types. To annotate arguments it is preferred
|
||
to use an abstract collection type such as <a class="reference internal" href="#typing.Sequence" title="typing.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a> or
|
||
<a class="reference internal" href="#typing.Iterable" title="typing.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>.</p>
|
||
<p>This type may be used as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">T</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'T'</span><span class="p">,</span> <span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">)</span>
|
||
|
||
<span class="k">def</span> <span class="nf">vec2</span><span class="p">(</span><span class="n">x</span><span class="p">:</span> <span class="n">T</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">T</span><span class="p">)</span> <span class="o">-></span> <span class="n">List</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
|
||
<span class="k">return</span> <span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">]</span>
|
||
|
||
<span class="k">def</span> <span class="nf">keep_positives</span><span class="p">(</span><span class="n">vector</span><span class="p">:</span> <span class="n">Sequence</span><span class="p">[</span><span class="n">T</span><span class="p">])</span> <span class="o">-></span> <span class="n">List</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
|
||
<span class="k">return</span> <span class="p">[</span><span class="n">item</span> <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">vector</span> <span class="k">if</span> <span class="n">item</span> <span class="o">></span> <span class="mi">0</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Set">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Set</code><span class="sig-paren">(</span><em>set, MutableSet[T]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Set" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">builtins.set</span></code></a>.
|
||
Useful for annotating return types. To annotate arguments it is preferred
|
||
to use an abstract collection type such as <a class="reference internal" href="#typing.AbstractSet" title="typing.AbstractSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractSet</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.FrozenSet">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">FrozenSet</code><span class="sig-paren">(</span><em>frozenset, AbstractSet[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.FrozenSet" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">builtins.frozenset</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.MappingView">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">MappingView</code><span class="sig-paren">(</span><em>Sized, Iterable[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.MappingView" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.MappingView" title="collections.abc.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.MappingView</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.KeysView">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">KeysView</code><span class="sig-paren">(</span><em>MappingView[KT_co], AbstractSet[KT_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.KeysView" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.KeysView" title="collections.abc.KeysView"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.KeysView</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ItemsView">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ItemsView</code><span class="sig-paren">(</span><em>MappingView, Generic[KT_co, VT_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.ItemsView" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.ItemsView" title="collections.abc.ItemsView"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.ItemsView</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ValuesView">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ValuesView</code><span class="sig-paren">(</span><em>MappingView[VT_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.ValuesView" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.ValuesView" title="collections.abc.ValuesView"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.ValuesView</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Awaitable">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Awaitable</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Awaitable" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Awaitable" title="collections.abc.Awaitable"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Awaitable</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Coroutine">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Coroutine</code><span class="sig-paren">(</span><em>Awaitable[V_co], Generic[T_co T_contra, V_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Coroutine" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.Coroutine" title="collections.abc.Coroutine"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Coroutine</span></code></a>.
|
||
The variance and order of type variables
|
||
correspond to those of <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a>, for example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Coroutine</span>
|
||
<span class="n">c</span> <span class="o">=</span> <span class="kc">None</span> <span class="c1"># type: Coroutine[List[str], str, int]</span>
|
||
<span class="o">...</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s1">'hi'</span><span class="p">)</span> <span class="c1"># type: List[str]</span>
|
||
<span class="k">async</span> <span class="k">def</span> <span class="nf">bar</span><span class="p">()</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="k">await</span> <span class="n">c</span> <span class="c1"># type: int</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.3.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.AsyncIterable">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">AsyncIterable</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.AsyncIterable" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.AsyncIterable" title="collections.abc.AsyncIterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.AsyncIterable</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.AsyncIterator">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">AsyncIterator</code><span class="sig-paren">(</span><em>AsyncIterable[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.AsyncIterator" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.abc.html#collections.abc.AsyncIterator" title="collections.abc.AsyncIterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.AsyncIterator</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ContextManager">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ContextManager</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.ContextManager" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="contextlib.html#contextlib.AbstractContextManager" title="contextlib.AbstractContextManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextlib.AbstractContextManager</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.0.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.AsyncContextManager">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">AsyncContextManager</code><span class="sig-paren">(</span><em>Generic[T_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.AsyncContextManager" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="contextlib.html#contextlib.AbstractAsyncContextManager" title="contextlib.AbstractAsyncContextManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextlib.AbstractAsyncContextManager</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Dict">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Dict</code><span class="sig-paren">(</span><em>dict, MutableMapping[KT, VT]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Dict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.
|
||
Useful for annotating return types. To annotate arguments it is preferred
|
||
to use an abstract collection type such as <a class="reference internal" href="#typing.Mapping" title="typing.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a>.</p>
|
||
<p>This type can be used as follows:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">count_words</span><span class="p">(</span><span class="n">text</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">]:</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.DefaultDict">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">DefaultDict</code><span class="sig-paren">(</span><em>collections.defaultdict, MutableMapping[KT, VT]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.DefaultDict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.html#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.defaultdict</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.OrderedDict">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">OrderedDict</code><span class="sig-paren">(</span><em>collections.OrderedDict, MutableMapping[KT, VT]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.OrderedDict" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.7.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Counter">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Counter</code><span class="sig-paren">(</span><em>collections.Counter, Dict[T, int]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Counter" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.Counter</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.1.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ChainMap">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ChainMap</code><span class="sig-paren">(</span><em>collections.ChainMap, MutableMapping[KT, VT]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.ChainMap" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generic version of <a class="reference internal" href="collections.html#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.ChainMap</span></code></a>.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.1.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Generator">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Generator</code><span class="sig-paren">(</span><em>Iterator[T_co], Generic[T_co, T_contra, V_co]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.Generator" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A generator can be annotated by the generic type
|
||
<code class="docutils literal notranslate"><span class="pre">Generator[YieldType,</span> <span class="pre">SendType,</span> <span class="pre">ReturnType]</span></code>. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">echo_round</span><span class="p">()</span> <span class="o">-></span> <span class="n">Generator</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">,</span> <span class="nb">str</span><span class="p">]:</span>
|
||
<span class="n">sent</span> <span class="o">=</span> <span class="k">yield</span> <span class="mi">0</span>
|
||
<span class="k">while</span> <span class="n">sent</span> <span class="o">>=</span> <span class="mi">0</span><span class="p">:</span>
|
||
<span class="n">sent</span> <span class="o">=</span> <span class="k">yield</span> <span class="nb">round</span><span class="p">(</span><span class="n">sent</span><span class="p">)</span>
|
||
<span class="k">return</span> <span class="s1">'Done'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that unlike many other generics in the typing module, the <code class="docutils literal notranslate"><span class="pre">SendType</span></code>
|
||
of <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> behaves contravariantly, not covariantly or
|
||
invariantly.</p>
|
||
<p>If your generator will only yield values, set the <code class="docutils literal notranslate"><span class="pre">SendType</span></code> and
|
||
<code class="docutils literal notranslate"><span class="pre">ReturnType</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">infinite_stream</span><span class="p">(</span><span class="n">start</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">Generator</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">]:</span>
|
||
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="n">start</span>
|
||
<span class="n">start</span> <span class="o">+=</span> <span class="mi">1</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Alternatively, annotate your generator as having a return type of
|
||
either <code class="docutils literal notranslate"><span class="pre">Iterable[YieldType]</span></code> or <code class="docutils literal notranslate"><span class="pre">Iterator[YieldType]</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">infinite_stream</span><span class="p">(</span><span class="n">start</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">Iterator</span><span class="p">[</span><span class="nb">int</span><span class="p">]:</span>
|
||
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="n">start</span>
|
||
<span class="n">start</span> <span class="o">+=</span> <span class="mi">1</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.AsyncGenerator">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">AsyncGenerator</code><span class="sig-paren">(</span><em>AsyncIterator[T_co], Generic[T_co, T_contra]</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.AsyncGenerator" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>An async generator can be annotated by the generic type
|
||
<code class="docutils literal notranslate"><span class="pre">AsyncGenerator[YieldType,</span> <span class="pre">SendType]</span></code>. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">echo_round</span><span class="p">()</span> <span class="o">-></span> <span class="n">AsyncGenerator</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">]:</span>
|
||
<span class="n">sent</span> <span class="o">=</span> <span class="k">yield</span> <span class="mi">0</span>
|
||
<span class="k">while</span> <span class="n">sent</span> <span class="o">>=</span> <span class="mf">0.0</span><span class="p">:</span>
|
||
<span class="n">rounded</span> <span class="o">=</span> <span class="k">await</span> <span class="nb">round</span><span class="p">(</span><span class="n">sent</span><span class="p">)</span>
|
||
<span class="n">sent</span> <span class="o">=</span> <span class="k">yield</span> <span class="n">rounded</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Unlike normal generators, async generators cannot return a value, so there
|
||
is no <code class="docutils literal notranslate"><span class="pre">ReturnType</span></code> type parameter. As with <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a>, the
|
||
<code class="docutils literal notranslate"><span class="pre">SendType</span></code> behaves contravariantly.</p>
|
||
<p>If your generator will only yield values, set the <code class="docutils literal notranslate"><span class="pre">SendType</span></code> to
|
||
<code class="docutils literal notranslate"><span class="pre">None</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">infinite_stream</span><span class="p">(</span><span class="n">start</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">AsyncGenerator</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="kc">None</span><span class="p">]:</span>
|
||
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="n">start</span>
|
||
<span class="n">start</span> <span class="o">=</span> <span class="k">await</span> <span class="n">increment</span><span class="p">(</span><span class="n">start</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Alternatively, annotate your generator as having a return type of
|
||
either <code class="docutils literal notranslate"><span class="pre">AsyncIterable[YieldType]</span></code> or <code class="docutils literal notranslate"><span class="pre">AsyncIterator[YieldType]</span></code>:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">infinite_stream</span><span class="p">(</span><span class="n">start</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">AsyncIterator</span><span class="p">[</span><span class="nb">int</span><span class="p">]:</span>
|
||
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||
<span class="k">yield</span> <span class="n">start</span>
|
||
<span class="n">start</span> <span class="o">=</span> <span class="k">await</span> <span class="n">increment</span><span class="p">(</span><span class="n">start</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.1.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Text">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Text</code><a class="headerlink" href="#typing.Text" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p><code class="docutils literal notranslate"><span class="pre">Text</span></code> is an alias for <code class="docutils literal notranslate"><span class="pre">str</span></code>. It is provided to supply a forward
|
||
compatible path for Python 2 code: in Python 2, <code class="docutils literal notranslate"><span class="pre">Text</span></code> is an alias for
|
||
<code class="docutils literal notranslate"><span class="pre">unicode</span></code>.</p>
|
||
<p>Use <code class="docutils literal notranslate"><span class="pre">Text</span></code> to indicate that a value must contain a unicode string in
|
||
a manner that is compatible with both Python 2 and Python 3:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">add_unicode_checkmark</span><span class="p">(</span><span class="n">text</span><span class="p">:</span> <span class="n">Text</span><span class="p">)</span> <span class="o">-></span> <span class="n">Text</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">text</span> <span class="o">+</span> <span class="sa">u</span><span class="s1">' </span><span class="se">\u2713</span><span class="s1">'</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.IO">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">IO</code><a class="headerlink" href="#typing.IO" title="Permalink to this definition">¶</a></dt>
|
||
<dt id="typing.TextIO">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">TextIO</code><a class="headerlink" href="#typing.TextIO" title="Permalink to this definition">¶</a></dt>
|
||
<dt id="typing.BinaryIO">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">BinaryIO</code><a class="headerlink" href="#typing.BinaryIO" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Generic type <code class="docutils literal notranslate"><span class="pre">IO[AnyStr]</span></code> and its subclasses <code class="docutils literal notranslate"><span class="pre">TextIO(IO[str])</span></code>
|
||
and <code class="docutils literal notranslate"><span class="pre">BinaryIO(IO[bytes])</span></code>
|
||
represent the types of I/O streams such as returned by
|
||
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.Pattern">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Pattern</code><a class="headerlink" href="#typing.Pattern" title="Permalink to this definition">¶</a></dt>
|
||
<dt id="typing.Match">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">Match</code><a class="headerlink" href="#typing.Match" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>These type aliases
|
||
correspond to the return types from <a class="reference internal" href="re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> and
|
||
<a class="reference internal" href="re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a>. These types (and the corresponding functions)
|
||
are generic in <code class="docutils literal notranslate"><span class="pre">AnyStr</span></code> and can be made specific by writing
|
||
<code class="docutils literal notranslate"><span class="pre">Pattern[str]</span></code>, <code class="docutils literal notranslate"><span class="pre">Pattern[bytes]</span></code>, <code class="docutils literal notranslate"><span class="pre">Match[str]</span></code>, or
|
||
<code class="docutils literal notranslate"><span class="pre">Match[bytes]</span></code>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.NamedTuple">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">NamedTuple</code><a class="headerlink" href="#typing.NamedTuple" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Typed version of <a class="reference internal" href="collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.namedtuple()</span></code></a>.</p>
|
||
<p>Usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
|
||
<span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
|
||
<span class="nb">id</span><span class="p">:</span> <span class="nb">int</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>This is equivalent to:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Employee</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Employee'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'name'</span><span class="p">,</span> <span class="s1">'id'</span><span class="p">])</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To give a field a default value, you can assign to it in the class body:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
|
||
<span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
|
||
<span class="nb">id</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span>
|
||
|
||
<span class="n">employee</span> <span class="o">=</span> <span class="n">Employee</span><span class="p">(</span><span class="s1">'Guido'</span><span class="p">)</span>
|
||
<span class="k">assert</span> <span class="n">employee</span><span class="o">.</span><span class="n">id</span> <span class="o">==</span> <span class="mi">3</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Fields with a default value must come after any fields without a default.</p>
|
||
<p>The resulting class has two extra attributes: <code class="docutils literal notranslate"><span class="pre">_field_types</span></code>,
|
||
giving a dict mapping field names to types, and <code class="docutils literal notranslate"><span class="pre">_field_defaults</span></code>, a dict
|
||
mapping field names to default values. (The field names are in the
|
||
<code class="docutils literal notranslate"><span class="pre">_fields</span></code> attribute, which is part of the namedtuple API.)</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">NamedTuple</span></code> subclasses can also have docstrings and methods:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
|
||
<span class="sd">"""Represents an employee."""</span>
|
||
<span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
|
||
<span class="nb">id</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span>
|
||
|
||
<span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">f</span><span class="s1">'<Employee </span><span class="si">{self.name}</span><span class="s1">, id=</span><span class="si">{self.id}</span><span class="s1">>'</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Backward-compatible usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Employee</span> <span class="o">=</span> <span class="n">NamedTuple</span><span class="p">(</span><span class="s1">'Employee'</span><span class="p">,</span> <span class="p">[(</span><span class="s1">'name'</span><span class="p">,</span> <span class="nb">str</span><span class="p">),</span> <span class="p">(</span><span class="s1">'id'</span><span class="p">,</span> <span class="nb">int</span><span class="p">)])</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.6: </span>Added support for <span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a> variable annotation syntax.</p>
|
||
</div>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.6.1: </span>Added support for default values, methods, and docstrings.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="class">
|
||
<dt id="typing.ForwardRef">
|
||
<em class="property">class </em><code class="descclassname">typing.</code><code class="descname">ForwardRef</code><a class="headerlink" href="#typing.ForwardRef" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A class used for internal typing representation of string forward references.
|
||
For example, <code class="docutils literal notranslate"><span class="pre">List["SomeClass"]</span></code> is implicitly transformed into
|
||
<code class="docutils literal notranslate"><span class="pre">List[ForwardRef("SomeClass")]</span></code>. This class should not be instantiated by
|
||
a user, but may be used by introspection tools.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.NewType">
|
||
<code class="descclassname">typing.</code><code class="descname">NewType</code><span class="sig-paren">(</span><em>typ</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.NewType" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A helper function to indicate a distinct types to a typechecker,
|
||
see <a class="reference internal" href="#distinct"><span class="std std-ref">NewType</span></a>. At runtime it returns a function that returns
|
||
its argument. Usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">UserId</span> <span class="o">=</span> <span class="n">NewType</span><span class="p">(</span><span class="s1">'UserId'</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span>
|
||
<span class="n">first_user</span> <span class="o">=</span> <span class="n">UserId</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.cast">
|
||
<code class="descclassname">typing.</code><code class="descname">cast</code><span class="sig-paren">(</span><em>typ</em>, <em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#typing.cast" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Cast a value to a type.</p>
|
||
<p>This returns the value unchanged. To the type checker this
|
||
signals that the return value has the designated type, but at
|
||
runtime we intentionally don’t check anything (we want this
|
||
to be as fast as possible).</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.get_type_hints">
|
||
<code class="descclassname">typing.</code><code class="descname">get_type_hints</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#typing.get_type_hints" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Return a dictionary containing type hints for a function, method, module
|
||
or class object.</p>
|
||
<p>This is often the same as <code class="docutils literal notranslate"><span class="pre">obj.__annotations__</span></code>. In addition,
|
||
forward references encoded as string literals are handled by evaluating
|
||
them in <code class="docutils literal notranslate"><span class="pre">globals</span></code> and <code class="docutils literal notranslate"><span class="pre">locals</span></code> namespaces. If necessary,
|
||
<code class="docutils literal notranslate"><span class="pre">Optional[t]</span></code> is added for function and method annotations if a default
|
||
value equal to <code class="docutils literal notranslate"><span class="pre">None</span></code> is set. For a class <code class="docutils literal notranslate"><span class="pre">C</span></code>, return
|
||
a dictionary constructed by merging all the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> along
|
||
<code class="docutils literal notranslate"><span class="pre">C.__mro__</span></code> in reverse order.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.overload">
|
||
<code class="descclassname">@</code><code class="descclassname">typing.</code><code class="descname">overload</code><a class="headerlink" href="#typing.overload" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>The <code class="docutils literal notranslate"><span class="pre">@overload</span></code> decorator allows describing functions and methods
|
||
that support multiple different combinations of argument types. A series
|
||
of <code class="docutils literal notranslate"><span class="pre">@overload</span></code>-decorated definitions must be followed by exactly one
|
||
non-<code class="docutils literal notranslate"><span class="pre">@overload</span></code>-decorated definition (for the same function/method).
|
||
The <code class="docutils literal notranslate"><span class="pre">@overload</span></code>-decorated definitions are for the benefit of the
|
||
type checker only, since they will be overwritten by the
|
||
non-<code class="docutils literal notranslate"><span class="pre">@overload</span></code>-decorated definition, while the latter is used at
|
||
runtime but should be ignored by a type checker. At runtime, calling
|
||
a <code class="docutils literal notranslate"><span class="pre">@overload</span></code>-decorated function directly will raise
|
||
<a class="reference internal" href="exceptions.html#NotImplementedError" title="NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>. An example of overload that gives a more
|
||
precise type than can be expressed using a union or a type variable:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@overload</span>
|
||
<span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">response</span><span class="p">:</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
<span class="nd">@overload</span>
|
||
<span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">response</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-></span> <span class="n">Tuple</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">]:</span>
|
||
<span class="o">...</span>
|
||
<span class="nd">@overload</span>
|
||
<span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">response</span><span class="p">:</span> <span class="nb">bytes</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
<span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">response</span><span class="p">):</span>
|
||
<span class="o"><</span><span class="n">actual</span> <span class="n">implementation</span><span class="o">></span>
|
||
</pre></div>
|
||
</div>
|
||
<p>See <span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> for details and comparison with other typing semantics.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.no_type_check">
|
||
<code class="descclassname">@</code><code class="descclassname">typing.</code><code class="descname">no_type_check</code><a class="headerlink" href="#typing.no_type_check" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Decorator to indicate that annotations are not type hints.</p>
|
||
<p>This works as class or function <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a>. With a class, it
|
||
applies recursively to all methods defined in that class (but not
|
||
to methods defined in its superclasses or subclasses).</p>
|
||
<p>This mutates the function(s) in place.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.no_type_check_decorator">
|
||
<code class="descclassname">@</code><code class="descclassname">typing.</code><code class="descname">no_type_check_decorator</code><a class="headerlink" href="#typing.no_type_check_decorator" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Decorator to give another decorator the <a class="reference internal" href="#typing.no_type_check" title="typing.no_type_check"><code class="xref py py-func docutils literal notranslate"><span class="pre">no_type_check()</span></code></a> effect.</p>
|
||
<p>This wraps the decorator with something that wraps the decorated
|
||
function in <a class="reference internal" href="#typing.no_type_check" title="typing.no_type_check"><code class="xref py py-func docutils literal notranslate"><span class="pre">no_type_check()</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="function">
|
||
<dt id="typing.type_check_only">
|
||
<code class="descclassname">@</code><code class="descclassname">typing.</code><code class="descname">type_check_only</code><a class="headerlink" href="#typing.type_check_only" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Decorator to mark a class or function to be unavailable at runtime.</p>
|
||
<p>This decorator is itself not available at runtime. It is mainly
|
||
intended to mark classes that are defined in type stub files if
|
||
an implementation returns an instance of a private class:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@type_check_only</span>
|
||
<span class="k">class</span> <span class="nc">Response</span><span class="p">:</span> <span class="c1"># private or not available at runtime</span>
|
||
<span class="n">code</span><span class="p">:</span> <span class="nb">int</span>
|
||
<span class="k">def</span> <span class="nf">get_header</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span> <span class="o">...</span>
|
||
|
||
<span class="k">def</span> <span class="nf">fetch_response</span><span class="p">()</span> <span class="o">-></span> <span class="n">Response</span><span class="p">:</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that returning instances of private classes is not recommended.
|
||
It is usually preferable to make such classes public.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.Any">
|
||
<code class="descclassname">typing.</code><code class="descname">Any</code><a class="headerlink" href="#typing.Any" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Special type indicating an unconstrained type.</p>
|
||
<ul class="simple">
|
||
<li><p>Every type is compatible with <a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a>.</p></li>
|
||
<li><p><a class="reference internal" href="#typing.Any" title="typing.Any"><code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code></a> is compatible with every type.</p></li>
|
||
</ul>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.NoReturn">
|
||
<code class="descclassname">typing.</code><code class="descname">NoReturn</code><a class="headerlink" href="#typing.NoReturn" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Special type indicating that a function never returns.
|
||
For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="k">import</span> <span class="n">NoReturn</span>
|
||
|
||
<span class="k">def</span> <span class="nf">stop</span><span class="p">()</span> <span class="o">-></span> <span class="n">NoReturn</span><span class="p">:</span>
|
||
<span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s1">'no way'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.4.</span></p>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.6.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.Union">
|
||
<code class="descclassname">typing.</code><code class="descname">Union</code><a class="headerlink" href="#typing.Union" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Union type; <code class="docutils literal notranslate"><span class="pre">Union[X,</span> <span class="pre">Y]</span></code> means either X or Y.</p>
|
||
<p>To define a union, use e.g. <code class="docutils literal notranslate"><span class="pre">Union[int,</span> <span class="pre">str]</span></code>. Details:</p>
|
||
<ul>
|
||
<li><p>The arguments must be types and there must be at least one.</p></li>
|
||
<li><p>Unions of unions are flattened, e.g.:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Union</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">],</span> <span class="nb">float</span><span class="p">]</span> <span class="o">==</span> <span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">,</span> <span class="nb">float</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><p>Unions of a single argument vanish, e.g.:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span> <span class="o">==</span> <span class="nb">int</span> <span class="c1"># The constructor actually returns int</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><p>Redundant arguments are skipped, e.g.:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">]</span> <span class="o">==</span> <span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><p>When comparing unions, the argument order is ignored, e.g.:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">]</span> <span class="o">==</span> <span class="n">Union</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><p>You cannot subclass or instantiate a union.</p></li>
|
||
<li><p>You cannot write <code class="docutils literal notranslate"><span class="pre">Union[X][Y]</span></code>.</p></li>
|
||
<li><p>You can use <code class="docutils literal notranslate"><span class="pre">Optional[X]</span></code> as a shorthand for <code class="docutils literal notranslate"><span class="pre">Union[X,</span> <span class="pre">None]</span></code>.</p></li>
|
||
</ul>
|
||
<div class="versionchanged">
|
||
<p><span class="versionmodified changed">Changed in version 3.7: </span>Don’t remove explicit subclasses from unions at runtime.</p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.Optional">
|
||
<code class="descclassname">typing.</code><code class="descname">Optional</code><a class="headerlink" href="#typing.Optional" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Optional type.</p>
|
||
<p><code class="docutils literal notranslate"><span class="pre">Optional[X]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">Union[X,</span> <span class="pre">None]</span></code>.</p>
|
||
<p>Note that this is not the same concept as an optional argument,
|
||
which is one that has a default. An optional argument with a
|
||
default does not require the <code class="docutils literal notranslate"><span class="pre">Optional</span></code> qualifier on its type
|
||
annotation just because it is optional. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">arg</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>On the other hand, if an explicit value of <code class="docutils literal notranslate"><span class="pre">None</span></code> is allowed, the
|
||
use of <code class="docutils literal notranslate"><span class="pre">Optional</span></code> is appropriate, whether the argument is optional
|
||
or not. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">arg</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.Tuple">
|
||
<code class="descclassname">typing.</code><code class="descname">Tuple</code><a class="headerlink" href="#typing.Tuple" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Tuple type; <code class="docutils literal notranslate"><span class="pre">Tuple[X,</span> <span class="pre">Y]</span></code> is the type of a tuple of two items
|
||
with the first item of type X and the second of type Y.</p>
|
||
<p>Example: <code class="docutils literal notranslate"><span class="pre">Tuple[T1,</span> <span class="pre">T2]</span></code> is a tuple of two elements corresponding
|
||
to type variables T1 and T2. <code class="docutils literal notranslate"><span class="pre">Tuple[int,</span> <span class="pre">float,</span> <span class="pre">str]</span></code> is a tuple
|
||
of an int, a float and a string.</p>
|
||
<p>To specify a variable-length tuple of homogeneous type,
|
||
use literal ellipsis, e.g. <code class="docutils literal notranslate"><span class="pre">Tuple[int,</span> <span class="pre">...]</span></code>. A plain <a class="reference internal" href="#typing.Tuple" title="typing.Tuple"><code class="xref py py-data docutils literal notranslate"><span class="pre">Tuple</span></code></a>
|
||
is equivalent to <code class="docutils literal notranslate"><span class="pre">Tuple[Any,</span> <span class="pre">...]</span></code>, and in turn to <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.Callable">
|
||
<code class="descclassname">typing.</code><code class="descname">Callable</code><a class="headerlink" href="#typing.Callable" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Callable type; <code class="docutils literal notranslate"><span class="pre">Callable[[int],</span> <span class="pre">str]</span></code> is a function of (int) -> str.</p>
|
||
<p>The subscription syntax must always be used with exactly two
|
||
values: the argument list and the return type. The argument list
|
||
must be a list of types or an ellipsis; the return type must be
|
||
a single type.</p>
|
||
<p>There is no syntax to indicate optional or keyword arguments;
|
||
such function types are rarely used as callback types.
|
||
<code class="docutils literal notranslate"><span class="pre">Callable[...,</span> <span class="pre">ReturnType]</span></code> (literal ellipsis) can be used to
|
||
type hint a callable taking any number of arguments and returning
|
||
<code class="docutils literal notranslate"><span class="pre">ReturnType</span></code>. A plain <a class="reference internal" href="#typing.Callable" title="typing.Callable"><code class="xref py py-data docutils literal notranslate"><span class="pre">Callable</span></code></a> is equivalent to
|
||
<code class="docutils literal notranslate"><span class="pre">Callable[...,</span> <span class="pre">Any]</span></code>, and in turn to
|
||
<a class="reference internal" href="collections.abc.html#collections.abc.Callable" title="collections.abc.Callable"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Callable</span></code></a>.</p>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.ClassVar">
|
||
<code class="descclassname">typing.</code><code class="descname">ClassVar</code><a class="headerlink" href="#typing.ClassVar" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>Special type construct to mark class variables.</p>
|
||
<p>As introduced in <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a>, a variable annotation wrapped in ClassVar
|
||
indicates that a given attribute is intended to be used as a class variable
|
||
and should not be set on instances of that class. Usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Starship</span><span class="p">:</span>
|
||
<span class="n">stats</span><span class="p">:</span> <span class="n">ClassVar</span><span class="p">[</span><span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">int</span><span class="p">]]</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># class variable</span>
|
||
<span class="n">damage</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">10</span> <span class="c1"># instance variable</span>
|
||
</pre></div>
|
||
</div>
|
||
<p><a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">ClassVar</span></code></a> accepts only types and cannot be further subscribed.</p>
|
||
<p><a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">ClassVar</span></code></a> is not a class itself, and should not
|
||
be used with <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> or <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>.
|
||
<a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">ClassVar</span></code></a> does not change Python runtime behavior, but
|
||
it can be used by third-party type checkers. For example, a type checker
|
||
might flag the following code as an error:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">enterprise_d</span> <span class="o">=</span> <span class="n">Starship</span><span class="p">(</span><span class="mi">3000</span><span class="p">)</span>
|
||
<span class="n">enterprise_d</span><span class="o">.</span><span class="n">stats</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># Error, setting class variable on instance</span>
|
||
<span class="n">Starship</span><span class="o">.</span><span class="n">stats</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># This is OK</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.3.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.AnyStr">
|
||
<code class="descclassname">typing.</code><code class="descname">AnyStr</code><a class="headerlink" href="#typing.AnyStr" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p><code class="docutils literal notranslate"><span class="pre">AnyStr</span></code> is a type variable defined as
|
||
<code class="docutils literal notranslate"><span class="pre">AnyStr</span> <span class="pre">=</span> <span class="pre">TypeVar('AnyStr',</span> <span class="pre">str,</span> <span class="pre">bytes)</span></code>.</p>
|
||
<p>It is meant to be used for functions that may accept any kind of string
|
||
without allowing different kinds of strings to mix. For example:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">concat</span><span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="n">AnyStr</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="n">AnyStr</span><span class="p">)</span> <span class="o">-></span> <span class="n">AnyStr</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>
|
||
|
||
<span class="n">concat</span><span class="p">(</span><span class="sa">u</span><span class="s2">"foo"</span><span class="p">,</span> <span class="sa">u</span><span class="s2">"bar"</span><span class="p">)</span> <span class="c1"># Ok, output has type 'unicode'</span>
|
||
<span class="n">concat</span><span class="p">(</span><span class="sa">b</span><span class="s2">"foo"</span><span class="p">,</span> <span class="sa">b</span><span class="s2">"bar"</span><span class="p">)</span> <span class="c1"># Ok, output has type 'bytes'</span>
|
||
<span class="n">concat</span><span class="p">(</span><span class="sa">u</span><span class="s2">"foo"</span><span class="p">,</span> <span class="sa">b</span><span class="s2">"bar"</span><span class="p">)</span> <span class="c1"># Error, cannot mix unicode and bytes</span>
|
||
</pre></div>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
<dl class="data">
|
||
<dt id="typing.TYPE_CHECKING">
|
||
<code class="descclassname">typing.</code><code class="descname">TYPE_CHECKING</code><a class="headerlink" href="#typing.TYPE_CHECKING" title="Permalink to this definition">¶</a></dt>
|
||
<dd><p>A special constant that is assumed to be <code class="docutils literal notranslate"><span class="pre">True</span></code> by 3rd party static
|
||
type checkers. It is <code class="docutils literal notranslate"><span class="pre">False</span></code> at runtime. Usage:</p>
|
||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">TYPE_CHECKING</span><span class="p">:</span>
|
||
<span class="kn">import</span> <span class="nn">expensive_mod</span>
|
||
|
||
<span class="k">def</span> <span class="nf">fun</span><span class="p">(</span><span class="n">arg</span><span class="p">:</span> <span class="s1">'expensive_mod.SomeType'</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
|
||
<span class="n">local_var</span><span class="p">:</span> <span class="n">expensive_mod</span><span class="o">.</span><span class="n">AnotherType</span> <span class="o">=</span> <span class="n">other_fun</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Note that the first type annotation must be enclosed in quotes, making it a
|
||
“forward reference”, to hide the <code class="docutils literal notranslate"><span class="pre">expensive_mod</span></code> reference from the
|
||
interpreter runtime. Type annotations for local variables are not
|
||
evaluated, so the second annotation does not need to be enclosed in quotes.</p>
|
||
<div class="versionadded">
|
||
<p><span class="versionmodified added">New in version 3.5.2.</span></p>
|
||
</div>
|
||
</dd></dl>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
|
||
<div class="sphinxsidebarwrapper">
|
||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||
<ul>
|
||
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">typing</span></code> — Support for type hints</a><ul>
|
||
<li><a class="reference internal" href="#type-aliases">Type aliases</a></li>
|
||
<li><a class="reference internal" href="#newtype">NewType</a></li>
|
||
<li><a class="reference internal" href="#callable">Callable</a></li>
|
||
<li><a class="reference internal" href="#generics">Generics</a></li>
|
||
<li><a class="reference internal" href="#user-defined-generic-types">User-defined generic types</a></li>
|
||
<li><a class="reference internal" href="#the-any-type">The <code class="xref py py-data docutils literal notranslate"><span class="pre">Any</span></code> type</a></li>
|
||
<li><a class="reference internal" href="#classes-functions-and-decorators">Classes, functions, and decorators</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
|
||
<h4>Previous topic</h4>
|
||
<p class="topless"><a href="development.html"
|
||
title="previous chapter">Development Tools</a></p>
|
||
<h4>Next topic</h4>
|
||
<p class="topless"><a href="pydoc.html"
|
||
title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></p>
|
||
<div role="note" aria-label="source link">
|
||
<h3>This Page</h3>
|
||
<ul class="this-page-menu">
|
||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||
<li>
|
||
<a href="https://github.com/python/cpython/blob/3.7/Doc/library/typing.rst"
|
||
rel="nofollow">Show Source
|
||
</a>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="clearer"></div>
|
||
</div>
|
||
<div class="related" role="navigation" aria-label="related navigation">
|
||
<h3>Navigation</h3>
|
||
<ul>
|
||
<li class="right" style="margin-right: 10px">
|
||
<a href="../genindex.html" title="General Index"
|
||
>index</a></li>
|
||
<li class="right" >
|
||
<a href="../py-modindex.html" title="Python Module Index"
|
||
>modules</a> |</li>
|
||
<li class="right" >
|
||
<a href="pydoc.html" title="pydoc — Documentation generator and online help system"
|
||
>next</a> |</li>
|
||
<li class="right" >
|
||
<a href="development.html" title="Development Tools"
|
||
>previous</a> |</li>
|
||
<li><img src="../_static/py.png" alt=""
|
||
style="vertical-align: middle; margin-top: -1px"/></li>
|
||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||
<li>
|
||
<span class="language_switcher_placeholder">en</span>
|
||
<span class="version_switcher_placeholder">3.7.4</span>
|
||
<a href="../index.html">Documentation </a> »
|
||
</li>
|
||
|
||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>
|
||
<li class="nav-item nav-item-2"><a href="development.html" >Development Tools</a> »</li>
|
||
<li class="right">
|
||
|
||
|
||
<div class="inline-search" style="display: none" role="search">
|
||
<form class="inline-search" action="../search.html" method="get">
|
||
<input placeholder="Quick search" type="text" name="q" />
|
||
<input type="submit" value="Go" />
|
||
<input type="hidden" name="check_keywords" value="yes" />
|
||
<input type="hidden" name="area" value="default" />
|
||
</form>
|
||
</div>
|
||
<script type="text/javascript">$('.inline-search').show(0);</script>
|
||
|
|
||
</li>
|
||
|
||
</ul>
|
||
</div>
|
||
<div class="footer">
|
||
© <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
|
||
<br />
|
||
The Python Software Foundation is a non-profit corporation.
|
||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||
<br />
|
||
Last updated on Jul 13, 2019.
|
||
<a href="../bugs.html">Found a bug</a>?
|
||
<br />
|
||
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
|
||
</div>
|
||
|
||
</body>
|
||
</html> |