Writing context managers using Python

We use. We forget. This is for myself so I remember the magic called Context Manager. You already must have used the "with statement" for file handling, threads, socket and other operations. I am going to talk about creating you OWN context managers.

The magic operator to be used is : @contextmanager. It can be imported from the module "contextlib"

To create a context manager, use the decorator contextlib.contextmanager


@contextlib.contextmanager
def getListCounts(x):
    try:
        from collections import Counter
        yield Counter(x)
    finally:
        print 'No of elements in the list : %d' % len(x)


Let's now use the above context manager 
   
Example 1:
>>> with getListCount([10, 10, 12]) as c:
 print "Element occurring the most is %d" % c.most_common()[0][0]

 
Element occurring the most is 10
No of elements in the list : 3

Example 2:
>>> with getListCount([10, 10, 12]) as c:
 print "Element occurring the least is %d" % c.most_common()[-1][0]

 
Element occurring the least is 12
No of elements in the list : 3

Popular posts from this blog

Why should you visit Kashmir sooner?

CNTLM in Office

How to run a Python program over the internet?