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
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)