coroutines and genexp

Co-routines are functions that can be stopped and resumed and can take data from multiple entry points. It is  very similar to “threading”. However in threading, the various threads work in a pre-emptive manner, hence there is a chance of resource locking.

The multitask module (can be installed with easy_install multitask) is a way of implementing co-routines. Another way is to use greenlet library.

>>> import multitask as m

>>> def fun1():

for i in range(2):

print ‘Fun 1 %d’ % i

yield i

>>> def fun2():

for i in range(4):

print ‘Fun 2 %d’ % i

yield i

>>> m.add(fun1())

>>> m.add(fun2())

>>> m.run()

Fun1 0

Fun2 0

Fun1 1

Fun2 1

Fun2 2

Fun2 3

>>>

>>>

Generator Expressions


These are very similar to list comprehension. They are a way to iterate over a generator in fewer lines of code.

* Use parenthesis () instead of square brackets []

* Replace yield

>>> i = (a**3 for a in range(10) if a % 2 != 0) # cubes of all odd numbers < 10

>>> i

< generator object <genexpr> at 0xb77374 >

>>> i.next()

1

>>>

>>> i.next()

27

>>>

>>> i.next()

125

>>>

>>> for e in i:

print e

343

729

>>>

Genexps yield values one at a time, so the entire sequence is NOT calculated at once (ahead of time). Thus the CPU assigns them a lower priority, so that more resources can be devoted to intensive tasks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: