Module Assign NameStore Str Assign NameStore Str Assign NameStore Str Assign NameStore Str Assign NameStore Str FunctionDef arguments args NameParam defaults body Assign NameStore BinOpMult ListLoad NameLoad Call NameLoad NameLoad FunctionDef arguments args NameParam NameParam defaults NameLoad body If CompareGtE NameLoad Call NameLoad NameLoad body Expr Yield NameLoad orelse For SubscriptStore NameLoad Index NameLoad Call SubscriptLoad NameLoad Index NameLoad body For NameStore Call NameLoad BinOpAdd NameLoad Num body Expr Yield NameLoad decorator_list For NameStore Call NameLoad Num body Expr Yield NameLoad decorator_list FunctionDef arguments args NameParam defaults body Assign NameStore Call NameLoad NameLoad Assign NameStore BinOpMult ListLoad NameLoad NameLoad FunctionDef arguments args NameParam NameParam defaults NameLoad body If CompareGtE NameLoad NameLoad body Expr Yield NameLoad orelse If BinOpMod BinOpSub NameLoad NameLoad Num body Assign NameStore BinOpAdd NameLoad Num For SubscriptStore NameLoad Index NameLoad Call SubscriptLoad NameLoad Index NameLoad body For NameStore Call NameLoad NameLoad body Expr Yield NameLoad orelse For NameStore Call NameLoad NameLoad body Expr Yield NameLoad decorator_list FunctionDef arguments args NameParam NameParam defaults NameLoad body Assert BoolOpAnd CompareLt NameLoad NameLoad CompareEq BinOpMod BinOpSub NameLoad NameLoad Num Num Assign TupleStore NameStore NameStore NameStore TupleLoad BinOpAdd NameLoad Num BinOpAdd NameLoad Num BinOpAdd NameLoad Num Assign TupleStore NameStore NameStore NameStore SubscriptLoad NameLoad Slice NameLoad NameLoad If CompareGtE NameLoad NameLoad body For SubscriptStore NameLoad Index NameLoad Call NameLoad body For SubscriptStore NameLoad Index NameLoad Call NameLoad body For SubscriptStore NameLoad Index NameLoad Call NameLoad body Expr Yield NameLoad orelse For SubscriptStore NameLoad Index NameLoad Call NameLoad body For SubscriptStore NameLoad Index NameLoad Call NameLoad body For SubscriptStore NameLoad Index NameLoad Call NameLoad body For NameStore Call NameLoad NameLoad body Expr Yield NameLoad decorator_list For NameStore Call NameLoad Num body Expr Yield NameLoad decorator_list FunctionDef arguments args NameParam defaults body Assign NameStore Call NameLoad NameLoad Assign NameStore BinOpMult ListLoad NameLoad NameLoad Assign NameStore BinOpMult ListLoad NameLoad NameLoad Assign NameStore NameLoad Assign NameStore Num While Num body TryExcept body While CompareLt NameLoad NameLoad body Assign NameStore SubscriptStore NameLoad Index NameLoad AttributeLoad Call SubscriptLoad NameLoad Index NameLoad attr Assign SubscriptStore NameLoad Index NameLoad Call NameLoad AugAssignAdd NameStore Num handlers ExceptHandler type NameLoad body Pass orelse Assert CompareEq NameLoad NameLoad Expr Yield NameLoad AugAssignSub NameStore Num While CompareGtE NameLoad Num body TryExcept body Assign SubscriptStore NameLoad Index NameLoad Call SubscriptLoad NameLoad Index NameLoad AugAssignAdd NameStore Num Break handlers ExceptHandler type NameLoad body AugAssignSub NameStore Num orelse Assert CompareLt NameLoad Num Break decorator_list ClassDef bases body FunctionDef arguments args NameParam NameParam defaults body Assign AttributeStore NameLoad attr NameLoad Assign NameStore Call NameLoad NameLoad Assign AttributeStore NameLoad attr ListLoad For NameStore NameLoad body Assign NameStore ListComp BinOpBitOr BinOpBitOr BinOpLShift Num NameLoad BinOpLShift Num BinOpSub BinOpAdd BinOpSub BinOpAdd NameLoad NameLoad NameLoad NameLoad Num BinOpLShift Num BinOpAdd BinOpAdd BinOpSub BinOpAdd NameLoad BinOpMult Num NameLoad Num NameLoad NameLoad comprehension NameStore NameLoad FunctionDef arguments args NameParam defaults NameLoad body For NameStore NameLoad body Assign NameStore SubscriptLoad NameLoad Index NameLoad If CompareEq BinOpBitAnd NameLoad AttributeLoad NameLoad attr Num body AugAssignBitOr AttributeStore NameLoad attr NameLoad Expr Yield NameLoad AugAssignBitAnd AttributeStore NameLoad attr UnaryOpInvert NameLoad decorator_list Expr Call AttributeLoad AttributeLoad NameLoad attr attr NameLoad decorator_list FunctionDef arguments args NameParam defaults body Assign AttributeStore NameLoad attr Num For NameStore Call NameLoad AttributeLoad NameLoad attr body Expr Yield NameLoad decorator_list FunctionDef arguments args NameParam NameParam defaults body Assign NameStore AttributeLoad NameLoad attr Assert CompareEq NameLoad Call NameLoad NameLoad Assign NameStore BinOpAdd Str BinOpMult Str NameLoad Print NameLoad For NameStore Call NameLoad NameLoad body Assign NameStore ListComp Str comprehension NameStore Call NameLoad NameLoad Assign SubscriptStore NameLoad Index SubscriptLoad NameLoad Index NameLoad Str Print BinOpAdd BinOpAdd Str Call AttributeLoad Str attr NameLoad Str Print NameLoad decorator_list decorator_list ClassDef bases body FunctionDef arguments args NameParam NameParam NameParam NameParam defaults Num body Assign TupleStore AttributeStore NameLoad attr AttributeStore NameLoad attr TupleLoad NameLoad NameLoad Assign NameStore AttributeStore NameLoad attr ListLoad FunctionDef arguments args NameParam NameParam defaults NameLoad body Assign NameStore NameStore Num For NameStore SubscriptLoad NameLoad Index NameLoad body Assign NameStore SubscriptLoad NameLoad Index NameLoad Expr Call AttributeLoad NameLoad attr NameLoad Assign NameStore Call NameLoad NameLoad If CompareEq NameLoad Num body AugAssignAdd NameStore Num orelse If CompareEq NameLoad Num body AugAssignAdd NameStore Num Return BoolOpAnd CompareEq NameLoad Num CompareLt NameLoad Num decorator_list FunctionDef arguments args NameParam defaults body For NameStore SubscriptLoad NameLoad Index NameLoad body Expr Call AttributeLoad SubscriptLoad NameLoad Index NameLoad attr NameLoad decorator_list FunctionDef arguments args defaults body If BoolOpOr CompareLt NameLoad Num CompareLt NameLoad Num body Return Assign NameStore Call AttributeLoad NameLoad attr Num Num Expr Call NameLoad NameLoad Assign AttributeStore NameLoad attr NameLoad Expr Yield NameLoad Expr Call NameLoad NameLoad decorator_list FunctionDef arguments args defaults body Assign NameStore Call AttributeLoad NameLoad attr Num Num Assert CompareEq AttributeLoad NameLoad attr NameLoad If BoolOpOr CompareLt NameLoad Num CompareLt NameLoad Num body Return Assert CompareEq Call NameLoad SubscriptLoad NameLoad Index NameLoad Num Assert CompareIn Call AttributeLoad NameLoad attr Num Num SubscriptLoad NameLoad Index NameLoad Assert CompareIn Call AttributeLoad NameLoad attr Num Num SubscriptLoad NameLoad Index NameLoad For TupleStore NameStore NameStore TupleLoad TupleLoad Num Num TupleLoad Num Num body Assign NameStore Call AttributeLoad NameLoad attr NameLoad NameLoad Assign NameStore Call AttributeLoad NameLoad attr BinOpSub Num NameLoad BinOpSub Num NameLoad Assign AttributeStore NameLoad attr NameLoad Expr Call NameLoad NameLoad Expr Call AttributeLoad SubscriptLoad NameLoad Index NameLoad attr NameLoad Assign AttributeStore NameLoad attr NameLoad Expr Yield NameLoad Expr Call AttributeLoad SubscriptLoad NameLoad Index NameLoad attr NameLoad Expr Call NameLoad NameLoad decorator_list FunctionDef arguments args NameParam defaults NameLoad body Assign NameStore ListLoad For NameStore SubscriptLoad NameLoad Index AttributeLoad NameLoad attr body Assign NameStore Call NameLoad SubscriptLoad NameLoad Index NameLoad Assert CompareGt NameLoad Num Str If CompareEq NameLoad Num body Assign NameStore ListLoad TupleLoad NameLoad NameLoad Break Expr Call AttributeLoad NameLoad attr TupleLoad NameLoad NameLoad orelse Expr Call AttributeLoad NameLoad attr For TupleStore NameStore NameStore NameLoad body If CompareNotEq NameLoad AttributeLoad NameLoad attr body If Call NameLoad NameLoad body Assign AttributeStore NameLoad attr NameLoad Expr Yield NameLoad Expr Call NameLoad NameLoad decorator_list FunctionDef arguments args NameParam NameParam NameParam defaults BinOpDiv BinOpSub NameLoad Num Num BinOpDiv BinOpSub NameLoad Num Num NameLoad body Assign NameStore ListLoad For NameStore SubscriptLoad NameLoad Index AttributeLoad NameLoad attr body Assign NameStore Call NameLoad SubscriptLoad NameLoad Index NameLoad Assert CompareGt NameLoad Num Str If CompareEq NameLoad Num body Assign NameStore ListLoad TupleLoad NameLoad Num NameLoad Break Assign TupleStore NameStore NameStore Call AttributeLoad NameLoad attr NameLoad Assign NameStore BinOpAdd BinOpPow BinOpSub NameLoad NameLoad Num BinOpPow BinOpSub NameLoad NameLoad Num Expr Call AttributeLoad NameLoad attr TupleLoad NameLoad UnaryOpUSub NameLoad NameLoad orelse Expr Call AttributeLoad NameLoad attr For TupleStore NameStore NameStore NameStore NameLoad body If CompareNotEq NameLoad AttributeLoad NameLoad attr body If Call NameLoad NameLoad body Assign AttributeStore NameLoad attr NameLoad Expr Yield NameLoad Expr Call NameLoad NameLoad decorator_list FunctionDef arguments args defaults body Assert CompareIn AttributeLoad NameLoad attr SubscriptLoad NameLoad Index AttributeLoad NameLoad attr Expr Yield AttributeLoad NameLoad attr decorator_list If CompareLt BinOpMult NameLoad NameLoad Num body Assign AttributeStore NameLoad attr ListLoad NameLoad orelse Assign AttributeStore NameLoad attr BinOpAdd BinOpAdd ListLoad NameLoad NameLoad BinOpMult ListLoad BoolOpOr BoolOpAnd NameLoad NameLoad NameLoad BinOpSub BinOpMult NameLoad NameLoad Num ListLoad NameLoad decorator_list FunctionDef arguments args NameParam NameParam NameParam defaults body Assert CompareLtELt Num NameLoad AttributeLoad NameLoad attr Assert CompareLtELt Num NameLoad AttributeLoad NameLoad attr Return BinOpAdd BinOpMult NameLoad AttributeLoad NameLoad attr NameLoad decorator_list FunctionDef arguments args NameParam NameParam defaults body Assert CompareLtELt Num NameLoad BinOpMult AttributeLoad NameLoad attr AttributeLoad NameLoad attr Return Call NameLoad NameLoad AttributeLoad NameLoad attr decorator_list FunctionDef arguments args NameParam defaults body Assign NameStore AttributeLoad NameLoad attr Delete SubscriptDel NameLoad Slice Assign TupleStore NameStore NameStore TupleLoad AttributeLoad NameLoad attr AttributeLoad NameLoad attr Assign NameStore AttributeLoad NameLoad attr Assign NameStore ListLoad TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num TupleLoad Num Num Assign NameStore Call NameLoad NameLoad For NameStore Call NameLoad NameLoad body For NameStore NameLoad body Assign NameStore ListComp Call NameLoad BinOpAdd NameLoad NameLoad BinOpAdd NameLoad NameLoad comprehension TupleStore NameStore NameStore NameLoad BoolOpAnd CompareLtELt Num BinOpAdd NameLoad NameLoad NameLoad CompareLtELt Num BinOpAdd NameLoad NameLoad NameLoad Expr Call AttributeLoad NameLoad attr NameLoad decorator_list FunctionDef arguments args NameParam defaults body Expr Call AttributeLoad NameLoad attr For NameStore Call NameLoad AttributeLoad NameLoad attr body Expr Yield NameLoad decorator_list FunctionDef arguments args NameParam NameParam defaults body Assign TupleStore NameStore NameStore TupleLoad AttributeLoad NameLoad attr AttributeLoad NameLoad attr Assert CompareEq Call NameLoad NameLoad BinOpMult NameLoad NameLoad Assign NameStore Call NameLoad Call NameLoad BinOpMult NameLoad NameLoad Assign NameStore BinOpAdd BinOpAdd Str Call NameLoad NameLoad Str Assign NameStore ListComp BinOpMult ListLoad NameLoad NameLoad comprehension NameStore Call NameLoad NameLoad Assign NameStore Num For NameStore NameLoad body Assign TupleStore NameStore NameStore Call AttributeLoad NameLoad attr NameLoad Assign SubscriptStore SubscriptLoad NameLoad Index NameLoad Index NameLoad BinOpMod NameLoad NameLoad AugAssignAdd NameStore Num Assign NameStore BinOpAdd Str BinOpMult BinOpAdd BinOpMult Str NameLoad Str NameLoad Print NameLoad For NameStore Call NameLoad NameLoad body Assign NameStore SubscriptLoad NameLoad Index NameLoad Print BinOpAdd BinOpAdd Str Call AttributeLoad Str attr NameLoad Str Print NameLoad decorator_list decorator_list Assign NameStore Str Assign NameStore Str Assign NameStore Str Assign NameStore Str Assign NameStore Dict Str Str Str Str Str Str Str Str Str NameLoad NameLoad NameLoad NameLoad NameLoad NameLoad NameLoad NameLoad NameLoad FunctionDef arguments args NameParam defaults NameLoad body ImportFrom alias alias Expr Call AttributeLoad NameLoad attr NameLoad NameLoad decorator_list FunctionDef arguments args defaults body Import alias ImportFrom alias Expr Call AttributeLoad NameLoad attr Expr Call NameLoad Num Expr Call AttributeLoad NameLoad attr Expr Call NameLoad Num Expr Call AttributeLoad NameLoad attr decorator_list If CompareEq NameLoad Str body Expr Call NameLoad Num
N/A N/A tutorial_tests 
Let's try a simple generator:

    >>> def f():
    ...    yield 1
    ...    yield 2

    >>> for i in f():
    ...     print i
    1
    2
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    2

"Falling off the end" stops the generator:

    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 2, in g
    StopIteration

"return" also stops the generator:

    >>> def f():
    ...     yield 1
    ...     return
    ...     yield 2 # never reached
    ...
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 3, in f
    StopIteration
    >>> g.next() # once stopped, can't be resumed
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

"raise StopIteration" stops the generator too:

    >>> def f():
    ...     yield 1
    ...     raise StopIteration
    ...     yield 2 # never reached
    ...
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
    >>> g.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

However, they are not exactly equivalent:

    >>> def g1():
    ...     try:
    ...         return
    ...     except:
    ...         yield 1
    ...
    >>> list(g1())
    []

    >>> def g2():
    ...     try:
    ...         raise StopIteration
    ...     except:
    ...         yield 42
    >>> print list(g2())
    [42]

This may be surprising at first:

    >>> def g3():
    ...     try:
    ...         return
    ...     finally:
    ...         yield 1
    ...
    >>> list(g3())
    [1]

Let's create an alternate range() function implemented as a generator:

    >>> def yrange(n):
    ...     for i in range(n):
    ...         yield i
    ...
    >>> list(yrange(5))
    [0, 1, 2, 3, 4]

Generators always return to the most recent caller:

    >>> def creator():
    ...     r = yrange(5)
    ...     print "creator", r.next()
    ...     return r
    ...
    >>> def caller():
    ...     r = creator()
    ...     for i in r:
    ...             print "caller", i
    ...
    >>> caller()
    creator 0
    caller 1
    caller 2
    caller 3
    caller 4

Generators can call other generators:

    >>> def zrange(n):
    ...     for i in yrange(n):
    ...         yield i
    ...
    >>> list(zrange(5))
    [0, 1, 2, 3, 4]

 N/A pep_tests 

Specification:  Yield

    Restriction:  A generator cannot be resumed while it is actively
    running:

    >>> def g():
    ...     i = me.next()
    ...     yield i
    >>> me = g()
    >>> me.next()
    Traceback (most recent call last):
     ...
      File "<string>", line 2, in g
    ValueError: generator already executing

Specification: Return

    Note that return isn't always equivalent to raising StopIteration:  the
    difference lies in how enclosing try/except constructs are treated.
    For example,

        >>> def f1():
        ...     try:
        ...         return
        ...     except:
        ...        yield 1
        >>> print list(f1())
        []

    because, as in any function, return simply exits, but

        >>> def f2():
        ...     try:
        ...         raise StopIteration
        ...     except:
        ...         yield 42
        >>> print list(f2())
        [42]

    because StopIteration is captured by a bare "except", as is any
    exception.

Specification: Generators and Exception Propagation

    >>> def f():
    ...     return 1//0
    >>> def g():
    ...     yield f()  # the zero division exception propagates
    ...     yield 42   # and we'll never get here
    >>> k = g()
    >>> k.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 2, in g
      File "<stdin>", line 2, in f
    ZeroDivisionError: integer division or modulo by zero
    >>> k.next()  # and the generator cannot be resumed
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
    >>>

Specification: Try/Except/Finally

    >>> def f():
    ...     try:
    ...         yield 1
    ...         try:
    ...             yield 2
    ...             1//0
    ...             yield 3  # never get here
    ...         except ZeroDivisionError:
    ...             yield 4
    ...             yield 5
    ...             raise
    ...         except:
    ...             yield 6
    ...         yield 7     # the "raise" above stops this
    ...     except:
    ...         yield 8
    ...     yield 9
    ...     try:
    ...         x = 12
    ...     finally:
    ...         yield 10
    ...     yield 11
    >>> print list(f())
    [1, 2, 4, 5, 8, 9, 10, 11]
    >>>

Guido's binary tree example.

    >>> # A binary tree class.
    >>> class Tree:
    ...
    ...     def __init__(self, label, left=None, right=None):
    ...         self.label = label
    ...         self.left = left
    ...         self.right = right
    ...
    ...     def __repr__(self, level=0, indent="    "):
    ...         s = level*indent + repr(self.label)
    ...         if self.left:
    ...             s = s + "\n" + self.left.__repr__(level+1, indent)
    ...         if self.right:
    ...             s = s + "\n" + self.right.__repr__(level+1, indent)
    ...         return s
    ...
    ...     def __iter__(self):
    ...         return inorder(self)

    >>> # Create a Tree from a list.
    >>> def tree(list):
    ...     n = len(list)
    ...     if n == 0:
    ...         return []
    ...     i = n // 2
    ...     return Tree(list[i], tree(list[:i]), tree(list[i+1:]))

    >>> # Show it off: create a tree.
    >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    >>> # A recursive generator that generates Tree labels in in-order.
    >>> def inorder(t):
    ...     if t:
    ...         for x in inorder(t.left):
    ...             yield x
    ...         yield t.label
    ...         for x in inorder(t.right):
    ...             yield x

    >>> # Show it off: create a tree.
    >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    >>> # Print the nodes of the tree in in-order.
    >>> for x in t:
    ...     print x,
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

    >>> # A non-recursive generator.
    >>> def inorder(node):
    ...     stack = []
    ...     while node:
    ...         while node.left:
    ...             stack.append(node)
    ...             node = node.left
    ...         yield node.label
    ...         while not node.right:
    ...             try:
    ...                 node = stack.pop()
    ...             except IndexError:
    ...                 return
    ...             yield node.label
    ...         node = node.right

    >>> # Exercise the non-recursive generator.
    >>> for x in t:
    ...     print x,
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

 N/A email_tests 

The difference between yielding None and returning it.

>>> def g():
...     for i in range(3):
...         yield None
...     yield None
...     return
>>> list(g())
[None, None, None, None]

Ensure that explicitly raising StopIteration acts like any other exception
in try/except, not like a return.

>>> def g():
...     yield 1
...     try:
...         raise StopIteration
...     except:
...         yield 2
...     yield 3
>>> list(g())
[1, 2, 3]

Next one was posted to c.l.py.

>>> def gcomb(x, k):
...     "Generate all combinations of k elements from list x."
...
...     if k > len(x):
...         return
...     if k == 0:
...         yield []
...     else:
...         first, rest = x[0], x[1:]
...         # A combination does or doesn't contain first.
...         # If it does, the remainder is a k-1 comb of rest.
...         for c in gcomb(rest, k-1):
...             c.insert(0, first)
...             yield c
...         # If it doesn't contain first, it's a k comb of rest.
...         for c in gcomb(rest, k):
...             yield c

>>> seq = range(1, 5)
>>> for k in range(len(seq) + 2):
...     print "%d-combs of %s:" % (k, seq)
...     for c in gcomb(seq, k):
...         print "   ", c
0-combs of [1, 2, 3, 4]:
    []
1-combs of [1, 2, 3, 4]:
    [1]
    [2]
    [3]
    [4]
2-combs of [1, 2, 3, 4]:
    [1, 2]
    [1, 3]
    [1, 4]
    [2, 3]
    [2, 4]
    [3, 4]
3-combs of [1, 2, 3, 4]:
    [1, 2, 3]
    [1, 2, 4]
    [1, 3, 4]
    [2, 3, 4]
4-combs of [1, 2, 3, 4]:
    [1, 2, 3, 4]
5-combs of [1, 2, 3, 4]:

From the Iterators list, about the types of these things.

>>> def g():
...     yield 1
...
>>> type(g)
<type 'function'>
>>> i = g()
>>> type(i)
<type 'generator'>
>>> [s for s in dir(i) if not s.startswith('_')]
['close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
>>> print i.next.__doc__
x.next() -> the next value, or raise StopIteration
>>> iter(i) is i
True
>>> import types
>>> isinstance(i, types.GeneratorType)
True

And more, added later.

>>> i.gi_running
0
>>> type(i.gi_frame)
<type 'frame'>
>>> i.gi_running = 42
Traceback (most recent call last):
  ...
TypeError: readonly attribute
>>> def g():
...     yield me.gi_running
>>> me = g()
>>> me.gi_running
0
>>> me.next()
1
>>> me.gi_running
0

A clever union-find implementation from c.l.py, due to David Eppstein.
Sent: Friday, June 29, 2001 12:16 PM
To: python-list@python.org
Subject: Re: PEP 255: Simple Generators

>>> class disjointSet:
...     def __init__(self, name):
...         self.name = name
...         self.parent = None
...         self.generator = self.generate()
...
...     def generate(self):
...         while not self.parent:
...             yield self
...         for x in self.parent.generator:
...             yield x
...
...     def find(self):
...         return self.generator.next()
...
...     def union(self, parent):
...         if self.parent:
...             raise ValueError("Sorry, I'm not a root!")
...         self.parent = parent
...
...     def __str__(self):
...         return self.name

>>> names = "ABCDEFGHIJKLM"
>>> sets = [disjointSet(name) for name in names]
>>> roots = sets[:]

>>> import random
>>> gen = random.WichmannHill(42)
>>> while 1:
...     for s in sets:
...         print "%s->%s" % (s, s.find()),
...     print
...     if len(roots) > 1:
...         s1 = gen.choice(roots)
...         roots.remove(s1)
...         s2 = gen.choice(roots)
...         s1.union(s2)
...         print "merged", s1, "into", s2
...     else:
...         break
A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged D into G
A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged C into F
A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged L into A
A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M
merged H into E
A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged B into E
A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged J into G
A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M
merged E into G
A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M
merged M into G
A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G
merged I into K
A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G
merged K into A
A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G
merged F into A
A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G
merged A into G
A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G

 N/A fun_tests 

Build up to a recursive Sieve of Eratosthenes generator.

>>> def firstn(g, n):
...     return [g.next() for i in range(n)]

>>> def intsfrom(i):
...     while 1:
...         yield i
...         i += 1

>>> firstn(intsfrom(5), 7)
[5, 6, 7, 8, 9, 10, 11]

>>> def exclude_multiples(n, ints):
...     for i in ints:
...         if i % n:
...             yield i

>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
[1, 2, 4, 5, 7, 8]

>>> def sieve(ints):
...     prime = ints.next()
...     yield prime
...     not_divisible_by_prime = exclude_multiples(prime, ints)
...     for p in sieve(not_divisible_by_prime):
...         yield p

>>> primes = sieve(intsfrom(2))
>>> firstn(primes, 20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]


Another famous problem:  generate all integers of the form
    2**i * 3**j  * 5**k
in increasing order, where i,j,k >= 0.  Trickier than it may look at first!
Try writing it without generators, and correctly, and without generating
3 internal results for each result output.

>>> def times(n, g):
...     for i in g:
...         yield n * i
>>> firstn(times(10, intsfrom(1)), 10)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

>>> def merge(g, h):
...     ng = g.next()
...     nh = h.next()
...     while 1:
...         if ng < nh:
...             yield ng
...             ng = g.next()
...         elif ng > nh:
...             yield nh
...             nh = h.next()
...         else:
...             yield ng
...             ng = g.next()
...             nh = h.next()

The following works, but is doing a whale of a lot of redundant work --
it's not clear how to get the internal uses of m235 to share a single
generator.  Note that me_times2 (etc) each need to see every element in the
result sequence.  So this is an example where lazy lists are more natural
(you can look at the head of a lazy list any number of times).

>>> def m235():
...     yield 1
...     me_times2 = times(2, m235())
...     me_times3 = times(3, m235())
...     me_times5 = times(5, m235())
...     for i in merge(merge(me_times2,
...                          me_times3),
...                    me_times5):
...         yield i

Don't print "too many" of these -- the implementation above is extremely
inefficient:  each call of m235() leads to 3 recursive calls, and in
turn each of those 3 more, and so on, and so on, until we've descended
enough levels to satisfy the print stmts.  Very odd:  when I printed 5
lines of results below, this managed to screw up Win98's malloc in "the
usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
address space, and it *looked* like a very slow leak.

>>> result = m235()
>>> for i in range(3):
...     print firstn(result, 15)
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]

Heh.  Here's one way to get a shared list, complete with an excruciating
namespace renaming trick.  The *pretty* part is that the times() and merge()
functions can be reused as-is, because they only assume their stream
arguments are iterable -- a LazyList is the same as a generator to times().

>>> class LazyList:
...     def __init__(self, g):
...         self.sofar = []
...         self.fetch = g.next
...
...     def __getitem__(self, i):
...         sofar, fetch = self.sofar, self.fetch
...         while i >= len(sofar):
...             sofar.append(fetch())
...         return sofar[i]

>>> def m235():
...     yield 1
...     # Gack:  m235 below actually refers to a LazyList.
...     me_times2 = times(2, m235)
...     me_times3 = times(3, m235)
...     me_times5 = times(5, m235)
...     for i in merge(merge(me_times2,
...                          me_times3),
...                    me_times5):
...         yield i

Print as many of these as you like -- *this* implementation is memory-
efficient.

>>> m235 = LazyList(m235())
>>> for i in range(5):
...     print [m235[j] for j in range(15*i, 15*(i+1))]
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]

Ye olde Fibonacci generator, LazyList style.

>>> def fibgen(a, b):
...
...     def sum(g, h):
...         while 1:
...             yield g.next() + h.next()
...
...     def tail(g):
...         g.next()    # throw first away
...         for x in g:
...             yield x
...
...     yield a
...     yield b
...     for s in sum(iter(fib),
...                  tail(iter(fib))):
...         yield s

>>> fib = LazyList(fibgen(1, 2))
>>> firstn(iter(fib), 17)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]


Running after your tail with itertools.tee (new in version 2.4)

The algorithms "m235" (Hamming) and Fibonacci presented above are both
examples of a whole family of FP (functional programming) algorithms
where a function produces and returns a list while the production algorithm
suppose the list as already produced by recursively calling itself.
For these algorithms to work, they must:

- produce at least a first element without presupposing the existence of
  the rest of the list
- produce their elements in a lazy manner

To work efficiently, the beginning of the list must not be recomputed over
and over again. This is ensured in most FP languages as a built-in feature.
In python, we have to explicitly maintain a list of already computed results
and abandon genuine recursivity.

This is what had been attempted above with the LazyList class. One problem
with that class is that it keeps a list of all of the generated results and
therefore continually grows. This partially defeats the goal of the generator
concept, viz. produce the results only as needed instead of producing them
all and thereby wasting memory.

Thanks to itertools.tee, it is now clear "how to get the internal uses of
m235 to share a single generator".

>>> from itertools import tee
>>> def m235():
...     def _m235():
...         yield 1
...         for n in merge(times(2, m2),
...                        merge(times(3, m3),
...                              times(5, m5))):
...             yield n
...     m1 = _m235()
...     m2, m3, m5, mRes = tee(m1, 4)
...     return mRes

>>> it = m235()
>>> for i in range(5):
...     print firstn(it, 15)
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]

The "tee" function does just what we want. It internally keeps a generated
result for as long as it has not been "consumed" from all of the duplicated
iterators, whereupon it is deleted. You can therefore print the hamming
sequence during hours without increasing memory usage, or very little.

The beauty of it is that recursive running-after-their-tail FP algorithms
are quite straightforwardly expressed with this Python idiom.

Ye olde Fibonacci generator, tee style.

>>> def fib():
...
...     def _isum(g, h):
...         while 1:
...             yield g.next() + h.next()
...
...     def _fib():
...         yield 1
...         yield 2
...         fibTail.next() # throw first away
...         for res in _isum(fibHead, fibTail):
...             yield res
...
...     realfib = _fib()
...     fibHead, fibTail, fibRes = tee(realfib, 3)
...     return fibRes

>>> firstn(fib(), 17)
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]

 N/A syntax_tests 

>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
...     return 22
...     yield 1
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[0]>, line 3)

>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
...     yield 1
...     return 22
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[1]>, line 3)

"return None" is not the same as "return" in a generator:

>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
...     yield 1
...     return None
Traceback (most recent call last):
  ..
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[2]>, line 3)

These are fine:

>>> def f():
...     yield 1
...     return

>>> def f():
...     try:
...         yield 1
...     finally:
...         pass

>>> def f():
...     try:
...         try:
...             1//0
...         except ZeroDivisionError:
...             yield 666
...         except:
...             pass
...     finally:
...         pass

>>> def f():
...     try:
...         try:
...             yield 12
...             1//0
...         except ZeroDivisionError:
...             yield 666
...         except:
...             try:
...                 x = 12
...             finally:
...                 yield 12
...     except:
...         return
>>> list(f())
[12, 666]

>>> def f():
...    yield
>>> type(f())
<type 'generator'>


>>> def f():
...    if 0:
...        yield
>>> type(f())
<type 'generator'>


>>> def f():
...     if 0:
...         yield 1
>>> type(f())
<type 'generator'>

>>> def f():
...    if "":
...        yield None
>>> type(f())
<type 'generator'>

>>> def f():
...     return
...     try:
...         if x==4:
...             pass
...         elif 0:
...             try:
...                 1//0
...             except SyntaxError:
...                 pass
...             else:
...                 if 0:
...                     while 12:
...                         x += 1
...                         yield 2 # don't blink
...                         f(a, b, c, d, e)
...         else:
...             pass
...     except:
...         x = 1
...     return
>>> type(f())
<type 'generator'>

>>> def f():
...     if 0:
...         def g():
...             yield 1
...
>>> type(f())
<type 'NoneType'>

>>> def f():
...     if 0:
...         class C:
...             def __init__(self):
...                 yield 1
...             def f(self):
...                 yield 2
>>> type(f())
<type 'NoneType'>

>>> def f():
...     if 0:
...         return
...     if 0:
...         yield 2
>>> type(f())
<type 'generator'>


>>> def f(): #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
...     if 0:
...         lambda x:  x        # shouldn't trigger here
...         return              # or here
...         def f(i):
...             return 2*i      # or here
...         if 0:
...             return 3        # but *this* sucks (line 8)
...     if 0:
...         yield 2             # because it's a generator (line 10)
Traceback (most recent call last):
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.syntax[24]>, line 10)

This one caused a crash (see SF bug 567538):

>>> def f():
...     for i in range(3):
...         try:
...             continue
...         finally:
...             yield i
...
>>> g = f()
>>> print g.next()
0
>>> print g.next()
1
>>> print g.next()
2
>>> print g.next()
Traceback (most recent call last):
StopIteration
 conjoin N/A N/A gs N/A N/A N/A values N/A N/A None N/A len gs gen N/A N/A i values N/A values N/A N/A N/A i N/A len gs N/A N/A N/A values N/A N/A N/A values N/A i N/A N/A gs N/A i N/A N/A x N/A gen N/A i 1 N/A N/A N/A x N/A N/A x N/A gen 0 N/A N/A N/A x N/A conjoin N/A N/A gs N/A N/A N/A n N/A len gs N/A values N/A N/A None n gen N/A N/A i values N/A values N/A N/A N/A i n N/A N/A N/A values N/A N/A N/A N/A n i 3 N/A N/A ip1 N/A i 1 N/A N/A values N/A i N/A N/A gs N/A i N/A N/A x N/A gen ip1 N/A N/A N/A x N/A N/A x N/A _gen3 i N/A N/A N/A x N/A _gen3 N/A N/A i values N/A values N/A N/A N/A N/A i n N/A N/A N/A n i 3 0 N/A N/A ip1 ip2 ip3 N/A N/A i 1 N/A i 2 N/A i 3 N/A N/A g g1 g2 N/A gs N/A i ip3 N/A N/A ip3 n N/A N/A N/A values N/A i N/A g N/A N/A N/A values N/A ip1 N/A g1 N/A N/A N/A values N/A ip2 N/A g2 N/A N/A N/A values N/A N/A N/A values N/A i N/A g N/A N/A N/A values N/A ip1 N/A g1 N/A N/A N/A values N/A ip2 N/A g2 N/A N/A x N/A _gen3 ip3 N/A N/A N/A x N/A N/A x N/A gen 0 N/A N/A N/A x N/A flat_conjoin N/A N/A gs N/A N/A N/A n N/A len gs N/A values N/A N/A None n N/A iters N/A N/A None n N/A _StopIteration StopIteration N/A i 0 N/A 1 N/A N/A N/A N/A N/A i n N/A N/A it N/A iters N/A i N/A N/A N/A gs N/A i next N/A N/A values N/A i N/A it N/A i 1 N/A N/A N/A _StopIteration N/A N/A N/A N/A N/A i n N/A N/A values N/A i 1 N/A N/A i 0 N/A N/A N/A N/A N/A values N/A i N/A N/A iters N/A i N/A i 1 N/A N/A N/A N/A _StopIteration N/A N/A i 1 N/A N/A N/A i 0 N/A N/A Queens N/A N/A __init__ N/A N/A self n N/A N/A N/A N/A self n n N/A rangen N/A range n N/A N/A self rowgenerators N/A N/A i rangen N/A N/A rowuses N/A N/A N/A N/A 1 j N/A 1 N/A N/A N/A N/A n i j n 1 N/A 1 N/A N/A N/A N/A n N/A 2 n 1 i j N/A j rangen rowgen N/A N/A rowuses N/A rowuses N/A N/A j rangen N/A N/A uses N/A rowuses N/A j N/A N/A N/A uses N/A self used 0 N/A N/A N/A self used uses N/A N/A j N/A N/A self used N/A uses N/A N/A N/A N/A N/A self rowgenerators append rowgen N/A solve N/A N/A self N/A N/A N/A N/A self used 0 N/A row2col N/A conjoin N/A self rowgenerators N/A N/A N/A row2col N/A printsolution N/A N/A self row2col N/A N/A N/A n N/A self n N/A N/A n N/A len row2col N/A sep N/A + N/A -+ n N/A sep N/A i N/A range n N/A N/A squares N/A N/A j N/A range n N/A N/A squares N/A N/A row2col N/A i Q N/A N/A N/A | N/A N/A | join squares | N/A sep N/A N/A Knights N/A N/A __init__ N/A N/A self m n hard N/A 0 N/A N/A N/A N/A self m N/A self n N/A m n N/A succs N/A self succs N/A remove_from_successors N/A N/A i0 len N/A len N/A N/A ne0 ne1 0 N/A i N/A succs N/A i0 N/A N/A s N/A succs N/A i N/A N/A N/A s remove i0 N/A e N/A len s N/A N/A e 0 N/A N/A ne0 1 N/A N/A N/A e 1 N/A N/A ne1 1 N/A N/A N/A ne0 0 N/A ne1 2 N/A add_to_successors N/A N/A i0 N/A N/A N/A i N/A succs N/A i0 N/A N/A N/A N/A N/A succs N/A i append i0 N/A first N/A N/A N/A N/A N/A N/A N/A m 1 N/A n 1 N/A N/A N/A corner N/A N/A self coords2index 0 0 N/A N/A remove_from_successors corner N/A N/A self lastij corner N/A N/A corner N/A N/A add_to_successors corner N/A second N/A N/A N/A N/A N/A corner N/A N/A self coords2index 0 0 N/A N/A N/A self lastij corner N/A N/A N/A m 3 N/A n 3 N/A N/A N/A N/A N/A len N/A succs N/A corner 2 N/A N/A N/A N/A self coords2index 1 2 N/A succs N/A corner N/A N/A N/A N/A self coords2index 2 1 N/A succs N/A corner N/A N/A i j N/A N/A 1 2 N/A 2 1 N/A N/A this N/A N/A self coords2index i j N/A final N/A N/A self coords2index N/A 3 i N/A 3 j N/A N/A self final final N/A N/A remove_from_successors this N/A N/A N/A N/A succs N/A final append corner N/A N/A self lastij this N/A N/A this N/A N/A N/A N/A succs N/A final remove corner N/A N/A add_to_successors this N/A advance N/A N/A len N/A len N/A N/A candidates N/A N/A i N/A succs N/A N/A self lastij N/A N/A e N/A len N/A succs N/A i N/A N/A e 0 else remove_from_successors() pruning flawed N/A N/A e 1 N/A N/A candidates N/A N/A e i N/A N/A N/A N/A candidates append N/A e i N/A N/A N/A N/A candidates sort N/A N/A e i candidates N/A N/A N/A i N/A self final N/A N/A N/A remove_from_successors i N/A N/A N/A self lastij i N/A N/A i N/A N/A add_to_successors i N/A advance_hard N/A N/A vmid hmid len N/A N/A N/A m 1 2.0 N/A N/A n 1 2.0 len N/A N/A candidates N/A N/A i N/A succs N/A N/A self lastij N/A N/A e N/A len N/A succs N/A i N/A N/A e 0 else remove_from_successors() pruning flawed N/A N/A e 1 N/A N/A candidates N/A N/A e 0 i N/A N/A N/A i1 j1 N/A N/A self index2coords i N/A d N/A N/A N/A i1 vmid 2 N/A N/A j1 hmid 2 N/A N/A N/A candidates append N/A e N/A d i N/A N/A N/A N/A candidates sort N/A N/A e d i candidates N/A N/A N/A i N/A self final N/A N/A N/A remove_from_successors i N/A N/A N/A self lastij i N/A N/A i N/A N/A add_to_successors i N/A last N/A N/A N/A N/A N/A N/A N/A self final N/A succs N/A N/A self lastij N/A N/A N/A self final N/A N/A N/A N/A m n 4 N/A N/A N/A self squaregenerators N/A first N/A N/A N/A self squaregenerators N/A N/A N/A first second N/A N/A N/A N/A hard advance_hard advance N/A N/A m n 3 N/A last N/A coords2index N/A N/A self i j N/A N/A N/A N/A 0 i N/A self m N/A N/A 0 j N/A self n N/A N/A N/A i N/A self n j N/A index2coords N/A N/A self index N/A N/A N/A N/A 0 index N/A N/A self m N/A self n N/A N/A divmod index N/A self n N/A _init_board N/A N/A self N/A N/A N/A succs N/A self succs N/A N/A succs N/A N/A N/A m n N/A N/A self m N/A self n N/A c2i N/A self coords2index N/A offsets N/A N/A 1 2 N/A 2 1 N/A 2 -1 N/A 1 -2 N/A -1 -2 N/A -2 -1 N/A -2 1 N/A -1 2 N/A rangen N/A range n N/A i N/A range m N/A N/A j rangen N/A N/A s N/A N/A c2i N/A i io N/A j jo N/A N/A io jo offsets N/A N/A 0 N/A i io m N/A 0 N/A j jo n N/A N/A N/A succs append s N/A solve N/A N/A self N/A N/A N/A N/A N/A self _init_board N/A x N/A conjoin N/A self squaregenerators N/A N/A N/A x N/A printsolution N/A N/A self x N/A N/A N/A N/A m n N/A N/A self m N/A self n N/A N/A N/A len x N/A m n N/A w N/A len N/A str N/A m n N/A format N/A N/A % N/A str w d N/A squares N/A N/A N/A None n N/A i N/A range m N/A k 1 N/A i x N/A N/A N/A i1 j1 N/A N/A self index2coords i N/A N/A N/A squares N/A i1 N/A j1 N/A format k N/A k 1 N/A sep N/A + N/A N/A N/A - w + n N/A sep N/A i N/A range m N/A N/A row N/A squares N/A i N/A N/A N/A | N/A N/A | join row | N/A sep N/A N/A N/A conjoin_tests 

Generate the 3-bit binary numbers in order.  This illustrates dumbest-
possible use of conjoin, just to generate the full cross-product.

>>> for c in conjoin([lambda: iter((0, 1))] * 3):
...     print c
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]

For efficiency in typical backtracking apps, conjoin() yields the same list
object each time.  So if you want to save away a full account of its
generated sequence, you need to copy its results.

>>> def gencopy(iterator):
...     for x in iterator:
...         yield x[:]

>>> for n in range(10):
...     all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
...     print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
0 1 True True
1 2 True True
2 4 True True
3 8 True True
4 16 True True
5 32 True True
6 64 True True
7 128 True True
8 256 True True
9 512 True True

And run an 8-queens solver.

>>> q = Queens(8)
>>> LIMIT = 2
>>> count = 0
>>> for row2col in q.solve():
...     count += 1
...     if count <= LIMIT:
...         print "Solution", count
...         q.printsolution(row2col)
Solution 1
+-+-+-+-+-+-+-+-+
|Q| | | | | | | |
+-+-+-+-+-+-+-+-+
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+
| | | | | | | |Q|
+-+-+-+-+-+-+-+-+
| | | | | |Q| | |
+-+-+-+-+-+-+-+-+
| | |Q| | | | | |
+-+-+-+-+-+-+-+-+
| | | | | | |Q| |
+-+-+-+-+-+-+-+-+
| |Q| | | | | | |
+-+-+-+-+-+-+-+-+
| | | |Q| | | | |
+-+-+-+-+-+-+-+-+
Solution 2
+-+-+-+-+-+-+-+-+
|Q| | | | | | | |
+-+-+-+-+-+-+-+-+
| | | | | |Q| | |
+-+-+-+-+-+-+-+-+
| | | | | | | |Q|
+-+-+-+-+-+-+-+-+
| | |Q| | | | | |
+-+-+-+-+-+-+-+-+
| | | | | | |Q| |
+-+-+-+-+-+-+-+-+
| | | |Q| | | | |
+-+-+-+-+-+-+-+-+
| |Q| | | | | | |
+-+-+-+-+-+-+-+-+
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+

>>> print count, "solutions in all."
92 solutions in all.

And run a Knight's Tour on a 10x10 board.  Note that there are about
20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.

>>> k = Knights(10, 10)
>>> LIMIT = 2
>>> count = 0
>>> for x in k.solve():
...     count += 1
...     if count <= LIMIT:
...         print "Solution", count
...         k.printsolution(x)
...     else:
...         break
Solution 1
+---+---+---+---+---+---+---+---+---+---+
|  1| 58| 27| 34|  3| 40| 29| 10|  5|  8|
+---+---+---+---+---+---+---+---+---+---+
| 26| 35|  2| 57| 28| 33|  4|  7| 30| 11|
+---+---+---+---+---+---+---+---+---+---+
| 59|100| 73| 36| 41| 56| 39| 32|  9|  6|
+---+---+---+---+---+---+---+---+---+---+
| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
+---+---+---+---+---+---+---+---+---+---+
| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
+---+---+---+---+---+---+---+---+---+---+
| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
+---+---+---+---+---+---+---+---+---+---+
| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
+---+---+---+---+---+---+---+---+---+---+
| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
+---+---+---+---+---+---+---+---+---+---+
| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
+---+---+---+---+---+---+---+---+---+---+
| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
+---+---+---+---+---+---+---+---+---+---+
Solution 2
+---+---+---+---+---+---+---+---+---+---+
|  1| 58| 27| 34|  3| 40| 29| 10|  5|  8|
+---+---+---+---+---+---+---+---+---+---+
| 26| 35|  2| 57| 28| 33|  4|  7| 30| 11|
+---+---+---+---+---+---+---+---+---+---+
| 59|100| 73| 36| 41| 56| 39| 32|  9|  6|
+---+---+---+---+---+---+---+---+---+---+
| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
+---+---+---+---+---+---+---+---+---+---+
| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
+---+---+---+---+---+---+---+---+---+---+
| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
+---+---+---+---+---+---+---+---+---+---+
| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
+---+---+---+---+---+---+---+---+---+---+
| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
+---+---+---+---+---+---+---+---+---+---+
| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
+---+---+---+---+---+---+---+---+---+---+
| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
+---+---+---+---+---+---+---+---+---+---+
 N/A weakref_tests Generators are weakly referencable:

>>> import weakref
>>> def gen():
...     yield 'foo!'
...
>>> wr = weakref.ref(gen)
>>> wr() is gen
True
>>> p = weakref.proxy(gen)

Generator-iterators are weakly referencable as well:

>>> gi = gen()
>>> wr = weakref.ref(gi)
>>> wr() is gi
True
>>> p = weakref.proxy(gi)
>>> list(p)
['foo!']

 N/A coroutine_tests Sending a value into a started generator:

>>> def f():
...     print (yield 1)
...     yield 2
>>> g = f()
>>> g.next()
1
>>> g.send(42)
42
2

Sending a value into a new generator produces a TypeError:

>>> f().send("foo")
Traceback (most recent call last):
...
TypeError: can't send non-None value to a just-started generator


Yield by itself yields None:

>>> def f(): yield
>>> list(f())
[None]



An obscene abuse of a yield expression within a generator expression:

>>> list((yield 21) for i in range(4))
[21, None, 21, None, 21, None, 21, None]

And a more sane, but still weird usage:

>>> def f(): list(i for i in [(yield 26)])
>>> type(f())
<type 'generator'>


A yield expression with augmented assignment.

>>> def coroutine(seq):
...     count = 0
...     while count < 200:
...         count += yield
...         seq.append(count)
>>> seq = []
>>> c = coroutine(seq)
>>> c.next()
>>> print seq
[]
>>> c.send(10)
>>> print seq
[10]
>>> c.send(10)
>>> print seq
[10, 20]
>>> c.send(10)
>>> print seq
[10, 20, 30]


Check some syntax errors for yield expressions:

>>> f=lambda: (yield 1),(yield 2) #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
Traceback (most recent call last):
  ...
SyntaxError: 'yield' outside function (<doctest test.test_generators.__test__.coroutine[21]>, line 1)

>>> def f(): return lambda x=(yield): 1 #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
Traceback (most recent call last):
  ...
SyntaxError: 'return' with argument inside generator (<doctest test.test_generators.__test__.coroutine[22]>, line 1)

>>> def f(): x = yield = y #doctest: +IGNORE_EXCEPTION_DETAIL, +NORMALIZE_WHITESPACE
Traceback (most recent call last):
  ...
SyntaxError: assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[23]>, line 1)

>>> def f(): (yield bar) = y #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
  ...
SyntaxError: can't assign to yield expression (<doctest test.test_generators.__test__.coroutine[24]>, line 1)

>>> def f(): (yield bar) += y #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
  ...
SyntaxError: augmented assignment to yield expression not possible (<doctest test.test_generators.__test__.coroutine[25]>, line 1)


Now check some throw() conditions:

>>> def f():
...     while True:
...         try:
...             print (yield)
...         except ValueError,v:
...             print "caught ValueError (%s)" % (v),
>>> import sys
>>> g = f()
>>> g.next()

>>> g.throw(ValueError) # type only
caught ValueError ()

>>> g.throw(ValueError("xyz"))  # value only
caught ValueError (xyz)

>>> g.throw(ValueError, ValueError(1))   # value+matching type
caught ValueError (1)

>>> g.throw(ValueError, TypeError(1))  # mismatched type, rewrapped
caught ValueError (1)

>>> g.throw(ValueError, ValueError(1), None)   # explicit None traceback
caught ValueError (1)

>>> g.throw(ValueError(1), "foo")       # bad args
Traceback (most recent call last):
  ...
TypeError: instance exception may not have a separate value

>>> g.throw(ValueError, "foo", 23)      # bad args #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
  ...
TypeError: throw() third argument must be a traceback object

>>> def throw(g,exc):
...     try:
...         raise exc
...     except:
...         g.throw(*sys.exc_info())
>>> throw(g,ValueError) # do it with traceback included
caught ValueError ()

>>> g.send(1)
1

>>> throw(g,TypeError)  # terminate the generator
Traceback (most recent call last):
  ...
TypeError

>>> print g.gi_frame
None

>>> g.send(2)
Traceback (most recent call last):
  ...
StopIteration

>>> g.throw(ValueError,6)       # throw on closed generator
Traceback (most recent call last):
  ...
ValueError: 6

>>> f().throw(ValueError,7)     # throw on just-opened generator
Traceback (most recent call last):
  ...
ValueError: 7

Now let's try closing a generator:

>>> def f():
...     try: yield
...     except GeneratorExit:
...         print "exiting"

>>> g = f()
>>> g.next()
>>> g.close()
exiting
>>> g.close()  # should be no-op now

>>> f().close()  # close on just-opened generator should be fine

>>> def f(): yield      # an even simpler generator
>>> f().close()         # close before opening
>>> g = f()
>>> g.next()
>>> g.close()           # close normally

And finalization. But we have to force the timing of GC here, since we are running on Jython:
>>> def f():
...     try: yield
...     finally:
...         print "exiting"

>>> g = f()
>>> g.next()
>>> del g; extra_collect()
exiting


Now let's try some ill-behaved generators:

>>> def f():
...     try: yield
...     except GeneratorExit:
...         yield "foo!"
>>> g = f()
>>> g.next()
>>> g.close()
Traceback (most recent call last):
  ...
RuntimeError: generator ignored GeneratorExit
>>> g.close()


Our ill-behaved code should be invoked during GC:

>>> import sys, StringIO
>>> old, sys.stderr = sys.stderr, StringIO.StringIO()
>>> g = f()
>>> g.next()
>>> del g; extra_collect()
>>> sys.stderr.getvalue().startswith(
...     "Exception RuntimeError"
... )
True
>>> sys.stderr = old


And errors thrown during closing should propagate:

>>> def f():
...     try: yield
...     except GeneratorExit:
...         raise TypeError("fie!")
>>> g = f()
>>> g.next()
>>> g.close()
Traceback (most recent call last):
  ...
TypeError: fie!


Ensure that various yield expression constructs make their
enclosing function a generator:

>>> def f(): x += yield
>>> type(f())
<type 'generator'>

>>> def f(): x = yield
>>> type(f())
<type 'generator'>

>>> def f(): lambda x=(yield): 1
>>> type(f())
<type 'generator'>

>>> def f(): x=(i for i in (yield) if (yield))
>>> type(f())
<type 'generator'>

>>> def f(d): d[(yield "a")] = d[(yield "b")] = 27
>>> data = [1,2]
>>> g = f(data)
>>> type(g)
<type 'generator'>
>>> g.send(None)
'a'
>>> data
[1, 2]
>>> g.send(0)
'b'
>>> data
[27, 2]
>>> try: g.send(1)
... except StopIteration: pass
>>> data
[27, 27]

 N/A refleaks_tests 
Prior to adding cycle-GC support to itertools.tee, this code would leak
references. We add it to the standard suite so the routine refleak-tests
would trigger if it starts being uncleanable again.

>>> import itertools
>>> def leak():
...     class gen:
...         def __iter__(self):
...             return self
...         def next(self):
...             return self.item
...     g = gen()
...     head, tail = itertools.tee(g)
...     g.item = head
...     return head
>>> it = leak()

Make sure to also test the involvement of the tee-internal teedataobject,
which stores returned items.

>>> item = it.next()



This test leaked at one point due to generator finalization/destruction.
It was copied from Lib/test/leakers/test_generator_cycle.py before the file
was removed.

>>> def leak():
...    def gen():
...        while True:
...            yield g
...    g = gen()

>>> leak()


These refleak tests should perhaps be in a testfile of their own,
test_generators just happened to be the test that drew these out.

 N/A __test__ N/A tut pep email fun syntax conjoin weakref coroutine refleaks tutorial_tests pep_tests email_tests fun_tests syntax_tests conjoin_tests weakref_tests coroutine_tests refleaks_tests test_main N/A N/A verbose N/A None N/A test test_support test_generators N/A N/A N/A test_support run_doctest test_generators verbose N/A extra_collect N/A N/A N/A N/A N/A gc time sleep N/A N/A N/A gc collect N/A N/A sleep 1 N/A N/A N/A gc collect N/A N/A sleep 0.1 N/A N/A N/A gc collect N/A N/A N/A __name__ __main__ N/A N/A N/A test_main 1