About

Swaroop C H is 29 years of age. He is a coder and startupper. He has previously worked at Yahoo!, Adobe, his own startup and Infibeam.

Read more about him

Views
Personal tools
COLLECTION
Collection

Talk:Python en:Exceptions

From Notes

Jump to: navigation, search

IMHO Leave the function+contextmanager stuff out. Just do:

with open("poem.txt") as f:
    for line in f:
        print(line, end='')

to show how to open a file while automatically closing the file

Swaroop said:

Great! Made this change, much better now :)

from "What's new in Python2.6/3.0", "with" is a control-flow structure. "The ‘with‘ statement is a control-flow structure whose basic structure is:".

with expression [as variable]:
    with-block

also context management protocol should be mentioned there.

here is a little example of "with as" statement,may be not so clear:

class test:
    def __enter__(self):
        print("enter")
        return 1
    def __exit__(self,*args):
        print("exit")
        return True 
#return False with re-raise the "with-block" exceptions or errors.
 
with test() as t:
    print("t is not the result of test(), it is __enter__ returned")
    print("t is 1, yes, it is {0}".format(t))
    raise NameError("Hi there")

__enter__ and __exit__ function construct "context management protocol" support for a class. "with as" statement first evaluate __enter__() and the function return a value to "t". then it begin to execute the "with-block",no matter the with-block successfully or not(raise exception or error), the __exit__()function will be executed. it can be used to do some clean up.just like try...finally...

if the __exit__() function return True, the exception or error happened in "with-block" is ignored, if it return False, it will be re-raised.

also, by "from contextlib import contextmanager", we will have a new function decorator "@contextmanager", then "yield" can be used just like a __enter__() func.


-- User:Cjacker

Thanks Cjacker, you are right that it deserves more explanation. I've expanded the How It Works section.

I have to eventually go over it again, but let me know if it should be further improved.

Thanks,

Swaroop 02:13, 16 January 2009 (UTC)