Saturday, 23 April 2011

Python 'with' statement

'with' statement is quite useful nice feature added to python 2.5. Good description is presented at Understanding Python's "with" statement. Following is an useful excerpt:
 
class controlled_execution:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down

    with controlled_execution() as thing:
         some code

or some more tangible example:

>>> with open("my.txt",'w') as f:
...    f.write('hello')
... 
>>> f
<closed file 'my.txt', mode 'w' at 0xb774b2e0>
root@kibo-kubuntu:~# ls
my.txt
root@kibo-kubuntu:~# cat my.txt ; echo
hello 

Nice and easy! huh?!

No comments:

Post a Comment