“with” statement in python.. what it do ?

Humble Devassy Chirammal Forums Python Programming “with” statement in python.. what it do ?

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1948 Reply
    Humble
    Keymaster

    Even-though “with” became common in code base, most of the people dont know or havent heard about it.. So, what is “with” used for…

    The “try”, “except”, “finally” keyword is pretty common and as everyone know “finally” used to be good place for lots of cleaning work.

    Quote:
    The with statement is used to wrap the execution of a block with methods defined by a context manager). This allows common try…except…finally usage patterns to be encapsulated for convenient reuse.

    An example would be:

    Opening a file, working on the file, then closing it:

    Code:
    with open(‘output.txt’, ‘w’) as f:
    f.write(‘i am here to explain with statement’)

    If you open a file with “with” statement, at end of the “nested block”, the “file will be automatically closed”.. You dont need to do any extra cleanup your own. Suppose, if an exception happened when “writing” to a file in above code block, you dont have to worry about “closing of the subjected file”.. That said, The with statement creates resources within a nested block. The resources can be used within the block. When the block exits the resources are cleanly released regardless of the result of the code in the nested block – that is whether the block exists normally or because of an exception.

    “with” works on context manager.. The context managers “__enter__()” and “__exit-__()” functions are performed at entry and exit.. Python will execute the code body, and no matter what happens in that code, it call the context managers __exit__ method.

    For more details please refer:
    http://www.python.org/dev/peps/pep-0343/

Viewing 1 post (of 1 total)
Reply To: “with” statement in python.. what it do ?
Your information: