Optional return type annotations?
<p>I have a function that will either return a generator (<code>types.GeneratorType</code>) or <code>list</code>, depending upon the value of an argument. For example:</p>

<pre><code>def foo(switch: bool) -&gt; list: # return type of list || types.GeneratorType
    ... # create some generator object named f1
    if switch:
        return list(f1)
    else:
        return f1
</code></pre>

<p>How do I tell it that I can optionally return a list or another type? Or, for that matter, what about a bunch of different types?</p>

<p>I've looked over <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">documentation on a module <code>typing</code></a> but haven't as of yet found any methods there that allow for this. I haven't been able to find any examples by Googling either.</p>

<p>The two solutions that immediately spring to mind are: </p>

<ol>
<li><p>Make a <a href="https://docs.python.org/3/library/typing.html#typing.Union" rel="nofollow"><code>Union</code></a> type</p>

<pre><code>def foo(switch: bool) -&gt; Union[list, GeneratorType]:
</code></pre>

<p>which means <em>"returns either list or generator"</em> (you could also use <a href="https://docs.python.org/3/library/typing.html#typing.Generator" rel="nofollow"><code>Generator</code></a> and <a href="https://docs.python.org/3/library/typing.html#typing.List" rel="nofollow"><code>List</code></a>); or</p></li>
<li><p>Type based on the behaviour you can expect from <em>either</em> return value, e.g. that they are <a href="https://docs.python.org/3/library/typing.html#typing.Iterable" rel="nofollow"><code>Iterable</code></a>:</p>

<pre><code>def foo(switch: bool) -&gt; Iterable:  
</code></pre></li>
</ol>

<p>In both cases you could also provide more detail: list or generator/iterable <em>of what?</em></p>

<p>That said, something that returns either a list or a generator sounds like an odd interface, and it would be helpful to provide a bit more context around what consumers of your function should expect to do with whatever they receive. It may be that:</p>

<ul>
<li>a single function with two different returns isn't the right interface design; or </li>
<li>rather than <code>list</code> you could use the more general <a href="https://docs.python.org/3/library/typing.html#typing.Sequence" rel="nofollow"><code>Sequence</code></a>, to permit e.g. <code>tuple</code>s to be used instead.</li>
</ul>

python python-3.x annotations type-hinting