[Level 2] How to use yield in Python

yield in python just pass the control to the parent.
if a() call b(),
in b and execute yield,
the control would back to a() util a call generator.next()
e.g.
#!/bin/env python
def foo():
    print 'start foo()'       ## only pass here when first time call .next()
    n = 3 
    for i in range(1,n+1):
        print 'in for()'
        print 'yield %s' % i 
        yield i               ## return i when call .next()
        print 'back to for()' ## start from here when call .next() again

if __name__ == '__main__': 
    print 'start main'
    print 'init main vars'
    f = foo()
    i = 0 
    n = 10
    print 'f: %s' % f 
    print 'i: %s' % i 
    print 'n: %s' % n 
    
    for x in range(0,n): 
        print 'f.next()'
        i = f.next()
        print 'print i'
        print i
        print 'in main'
    print 'call again f.next()'
    print f.next()
    print 'exit'
$ ./t1.py 
start main
init main vars
f: <generator object foo at 0xb73e69dc>
i: 0
n: 10
f.next()
start foo()
in for()
yield 1
print i
1
in main
f.next()
back to for()
in for()
yield 2
print i
2
in main
f.next()
back to for()
in for()
yield 3
print i
3
in main
f.next()
back to for()
Traceback (most recent call last):
  File "./t.py", line 23, in 
    i = f.next()
StopIteration
#!/bin/env python
def foo():
  for i in range(0,5):
    yield i

f = foo()

for n in f:
  print 'n=%s' % n 

$ ./t2.py 
n=0
n=1
n=2
n=3
n=4
Wish this helps. regards, Stanley Huang

Comments

Popular posts from this blog

[Level 1] Rar tool for Solaris.

[Level 2] iif in Python