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>Wouldn't it be better to pass "type" as an argument? </p>

<pre><code>def foo(switch: type) -&gt; list | tuple | gen_func
    ... # create some generator object named f1
    return switch(f1)

 foo(list) &gt; list type
 foo(tuple) &gt; tuple
 # And if you would want to get generator you would only need to provide
 gen = lambda func_result: (el for el in func_result)
 foo(gen)
</code></pre>

<p>Dont know if this is the case.</p>

python python-3.x annotations type-hinting