Return value in generator function Python 2
<p>I'm wondering how I can write a generator function that also has the option to return a value. In Python 2, you get the following error message if a generator function tries to return a value. <code>SyntaxError: 'return' with argument inside generator</code></p>

<p>Is it possible to write a function where I specify if I want to receive a generator or not?</p>

<p>For example:</p>

<pre><code>def f(generator=False):
    if generator:
        yield 3
    else:
        return 3
</code></pre>

<p>Mandatory reading: <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">Understanding Generators in Python</a></p>

<p>Key information: </p>

<blockquote>
  <p><code>yield</code> anywhere in a function makes it a generator.</p>
</blockquote>

<p>Function is marked as generator when code is parsed. Therefore, it's impossible to toggle function behavior (generator / not generator) based on argument passed in runtime.</p>

python