
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Context Manager Types
In python, the runtime context is supported by the with statement. The context is defined by the context manager. Using the context manager, we can create user defined classes to define the runtime context. It enters into the task before executing the statement body, and when the statement body is completed, it ends.
There are two different methods for context manager. These methods are −
Method __enter__()
The __enter__() method is used to enter into the runtime context. It will return either the current object or another related object. The returned value is bound to the identifier in as clause of the with statement.
Method __exit__(exc_type, exc_val, exc_tb)
The __exit__() method is used to return a Boolean type result. It indicates any exception that occurred. If there is one exception for the with statement, it will go to the end block.
Example Code
class MyFileManager: def __init__(self, fname): self.file_name = fname def __enter__(self): self.myFile = open(self.file_name, 'r') return self.myFile def __exit__(self, exc_type, exc_val, exc_tb): if self.myFile: self.myFile.close() with MyFileManager('sampleTextFile.txt') as myFile: x = myFile.read() print(x)
Output
Test File. We can store different contents in this file ~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]
- Related Articles
- Python Context Variables
- Program to implement seat reservation manager in Python
- Difference between Brand Manager and Marketing Manager
- How to install pandas using the python package manager?
- Difference between Android Activity Context and Application Context
- Difference Between a Program Manager and a Project Manager
- Perl Variable Context
- PHP Context Parameters
- Python Numeric Types
- Python Iterator Types
- Python Sequence Types
- Python Set Types
- Python Mapping Types
- Cloud Product Manager
- Entrepreneur Vs Manager
