title: Setting a limit on an infinite generator in Python
body: <p>I'm trying to make the below generator to be able to set an upper limit on the numbers returned.</p>
  
  <p>Calling <code>list(it.takewhile(lambda x: x &lt; 100, get_primes()))</code> returns a list of all primes under 100 as expected but <code>list(get_primes(100))</code> (which should return the same list in the same way) just returns with an empty list.</p>
  
  <p>Obviously, I could include an <code>if n and candidate&gt;=n: break</code> in the <code>for</code> loop but I'm mostly interested in why the <code>if n: return</code> construct doesn't work like I'm expecting it should. Shouldn't it just return the same <code>takewhile</code> iterator that works above? What am I overlooking here?</p>
  
  <pre><code>import itertools as it
  
  def get_primes(n=None):
      """
      Generates primes to a max of n.
  
      &gt;&gt;&gt; list(get_primes(100))
      [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
      """
      if n:
          return it.takewhile(lambda x: x &lt; n, get_primes())
      composites = {}
      yield 2
      for candidate in it.count(3, 2):
          prime_factor = composites.pop(candidate, None)
          if prime_factor is None:
              yield candidate
              composites[candidate**2] = candidate
          else:
              composite = candidate + 2*prime_factor
              while composite in composites:
                  composite += 2*prime_factor
              composites[composite] = prime_factor
  </code></pre>