Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Print Exception
Next article icon

__exit__ in Python

Last Updated : 25 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. Even if we do not release resources, context managers implicitly performs this task.

Refer the below article to get the idea about basics of Context Manager.

  • Context Manager

__exit__() method

This is a method of ContextManager class. The __exit__ method takes care of releasing the resources occupied with the current code snippet. This method must be executed no matter what after we are done with the resources. This method contains instructions for properly closing the resource handler so that the resource is freed for further use by other programs in the OS. If an exception is raised; its type, value, and traceback are passed as arguments to __exit__(). Otherwise, three None arguments are supplied. If the exception is suppressed, then the return value from the __exit__() method will be True, otherwise, False.

syntax: __exit__(self, exception_type, exception_value, exception_traceback) 

Parameters: 

  • exception_type: indicates class of exception. 
  • exception_value: indicates type of exception . like divide_by_zero error, floating_point_error, which are types of arithmetic exception. 
  • exception_traceback: traceback is a report which has all of the information needed to solve the exception.

# Example 1: 

Python3




# Python program creating a
# context manager
     
class ContextManager():
    def __init__(self):
        print('init method called')
             
    def __enter__(self):
        print('enter method called')
        return self
         
    def __exit__(self, exc_type, exc_value, exc_traceback):
        print('exit method called')
     
     
with ContextManager() as manager:
    print('with statement block')
 
 
Output
init method called enter method called with statement block exit method called 

# Example 2: Understanding parameters of __exit__(). We will create a context manager that will be used to divide two numbers. If the 

Python3




# Python program to demonstrate
# __exit__ method
 
 
class Divide:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
 
    def __enter__(self):
        print("Inside __enter__")
        return self
 
    def __exit__(self, exc_type, exc_value, traceback):
        print("\nInside __exit__")
        print("\nExecution type:", exc_type)
        print("\nExecution value:", exc_value)
        print("\nTraceback:", traceback)
 
    def divide_by_zero(self):
        # causes ZeroDivisionError exception
        print(self.num1 / self.num2)
 
 
# Driver's code
with Divide(3, 1) as r:
    r.divide_by_zero()
 
print("................................................")
 
# will raise a ZeroDivisionError
with Divide(3, 0) as r:
    r.divide_by_zero()
 
 

Output: 

Inside __enter__ 3.0  Inside __exit__  Execution type: None  Execution value: None  Traceback: None ................................................ Inside __enter__  Inside __exit__  Execution type:   Execution value: division by zero  Traceback:  Traceback (most recent call last):   File "gfg.py", line 32, in      r.divide_by_zero()   File "gfg.py", line 21, in divide_by_zero     print(self.num1 / self.num2) ZeroDivisionError: division by zero


Next Article
Python Print Exception
author
shaikameena
Improve
Article Tags :
  • Python
  • Python-Miscellaneous
Practice Tags :
  • python

Similar Reads

  • anext() in Python
    anext() is a built-in function that retrieves the next item from an asynchronous iterator, acting as the async version of next(). It is essential when working with async iterators and generators, offering more flexibility in asynchronous workflows. Note: anext() is available starting in Python 3.10.
    3 min read
  • exec() in Python
    exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be
    4 min read
  • Python Print Exception
    In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
    3 min read
  • __call__ in Python
    Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When this method is defined, calling an object (obj(arg1, arg2)) automatically triggers obj._
    4 min read
  • Gotchas in Python
    Python is a go-to language for most of the newcomers into the programming world. This is because it is fairly simple, highly in-demand, and ultimately powerful. But there are some cases which might confuse or rather trick a rookie coder. These are called "Gotchas"! Originating from the informal term
    5 min read
  • Null in Python
    In Python, None represents the absence of a value and is the only instance of the NoneType. It's often used as a placeholder for variables that don't hold meaningful data yet. Unlike 0, "", or [], which are actual values, None specifically means "no value" or "nothing." Example: [GFGTABS] Python a =
    3 min read
  • Type Hints in Python
    Type hints are a feature in Python that allow developers to annotate their code with expected types for variables and function arguments. This helps to improve code readability and provides an opportunity to catch errors before runtime using type checkers like mypy. Using Type Hints in Python1. Vari
    3 min read
  • Python | os._exit() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status wit
    2 min read
  • Python next() method
    Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. C/C++ Code l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2. It has been replaced
    4 min read
  • Destructors in Python
    Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences