With statement in Python
In python the with keyword is used when working with unmanaged resources (like file streams). The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks. This allows common try..except..finally usage patterns to be encapsulated for convenient reuse.
with expression [as variable]:
with-block
It's handy when you have two related operations which you'd like to execute as a pair, with a block of code in between. The classic example is opening a file , manipulating the file, then closing it:
try:
file_obj = open(my_file, 'w')
file_obj.write("Halo")
finally:
file_obj.close()
Using with statement , to open a file, process its contents, and make sure to close it, you can simply do:
with open(my_file, 'w') as file_obj:
file_obj.write("Halo")
The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement , the with statement would automatically close the file in those cases, too. Use with statement , when ever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.
Related Topics
- Python Interview Questions (Part 2)
- Python Interview Questions (Part 3)
- What is python used for?
- Is Python interpreted, or compiled, or both?
- Explain how python is interpreted
- How do I install pip on Windows?
- How do you protect Python source code?
- What are the disadvantages of the Python?
- How would you achieve web scraping in Python?
- How to Python Script executable on Unix
- What is the difference between .py and .pyc files?
- What is __init__.py used for in Python?
- What does __name__=='__main__' in Python mean?
- What is docstring in Python?
- What is the difference between runtime and compile time?
- How to use *args and **kwargs in Python
- Purpose of "/" and "//" operator in python?
- What is the purpose pass statement in python?
- Why isn't there a switch or case statement in Python?
- How does the ternary operator work in Python?
- What is the purpose of "self" in Python
- How do you debug a program in Python?
- What are literals in python?
- What is Python's parameter passing mechanism?
- What is the process of compilation and Loading in python?
- Global and Local Variables in Python
- Is there a tool to help find bugs or perform static analysis?
- What does the 'yield' keyword do in Python?
- Comparison Operators != is not equal to in Python
- What is the difference between 'is' and '==' in python
- What is the difference between = and == in Python?
- How are the functions help() and dir() different?
- Is all the memory freed when Python exits?
- Difference between Mutable and Immutable in Python
- Explain split() methods of "re" module in Python
- Accessor and Mutator methods in Python
- How to Implement an 'enum' in Python
- Important characteristics of Python Objects
- How to determine the type of instance and inheritance in Python
- How would you implement inheritance in Python?
- How is Inheritance and Overriding methods are related?
- How can you create a copy of an object in Python?
- How to avoid having class data shared among instances in Python?
- Static class variables in Python
- Difference between @staticmethod and @classmethod in Python
- How to Get a List of Class Attributes in Python
- Does Python supports interfaces like in Java or C#?
- What is used to create Unicode string in Python?
- Difference between lists and tuples in Python?
- What are differences between List and Dictionary in Python
- Different file processing modes supported by Python
- How do you append to a file in Python?
- What are the differences between the threading and multiprocessing?
- Is there any way to kill a Thread in Python?
- What is the use of lambda in Python?
- What is map, filter and reduce in python?
- Is monkey patching considered good programming practice?
- What is "typeerror: 'module' object is not callable"
- Python: TypeError: unhashable type: 'list'
- How to convert bytes to string in Python?
- What are metaclasses in Python?