Skip to main content

Understanding "with" keyword in python, on Python Hunter



Just like anything in python, keyword "with" is introduced in python to make the things little easy. Imagine a situation where you have to manage the resources e.g opening file and closing them after the code is executed on file. To achieve this sort of task we have to write the code as follow:


 Follow Python Hunter on youtube   Follow Python Hunter on twitter Follow on tumbl ( at your own risk ) check profile on linkedIn 






Code: - def fileOperation(fileName):     file=open("file.txt")     return file   try:     content=fileOperation("file.txt")     print(content.read()) except:     print("exception") finally:     content.close()
Download 


But if you do it often you could do this as follow to make the code reusable:





But why do you need to do this when you know that you have to execute the only for once. To answer this question python-dev team finally came up with following approach:
Note:- Make sure you have "file.txt" and python code file in same dir.

The "with" keyword replaces the try finally block. "with" keyword executes the openFileClass() context manager and internally calls the __enter__(self) method, and whatever is being returned from __enter__(self) method is being stored in target variable (in this example it is as file). and just like finally the __exit__(self,type,value,traceback) method executes and act as safe guard, it means that no matter what happens in the __enter__(self) method the  __exit__(self,type,value,traceback) is responsible to execute in any case.

NOTE:- No matter if there is any exception in code, the __exit__(self,type,value,traceback) will get executed for safe keeping and this is where your final work should be (e.g closing files)

Nesting of Contexts:-

Download full example

Download Other Useful Examples:-



know about the raise keyword? no? then follow this simple post to get through this.


Click here to understand the "raise" keyword.

Comments

  1. More posts on classes and inheritance will be uploaded soon, and regarding this current post if you face any issue please feel free to contact me on

    hitman47silent994c4@gmail.com

    Thanks.

    ReplyDelete
  2. Thanks for your tutorial, it's really helpful for beginners.

    ReplyDelete
    Replies
    1. Thanks aman, keep following the blog PythonHunter for more updates or google for pransukh.blogspot.in #pransukh

      Delete

Post a Comment

Thanks in anticipation.