Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining Python's '__enter__' and '__exit__'

I saw this in someone's code. What does it mean?

    def __enter__(self):         return self      def __exit__(self, type, value, tb):         self.stream.close() 

from __future__ import with_statement#for python2.5   class a(object):     def __enter__(self):         print 'sss'         return 'sss111'     def __exit__(self ,type, value, traceback):         print 'ok'         return False  with a() as s:     print s   print s 
like image 505
zjm1126 Avatar asked Dec 31 '09 07:12

zjm1126


People also ask

What does __ exit __ do in Python?

__exit__ in Python 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.

How do you exit a class in Python?

Program to stop code execution in python To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.

Which methods are invoked on entering into exiting from the block of code written in with statement Coursehero?

The __enter__ method is called at the start of the with block while __exit__ method is called at the end. The 'with' statement can only be used by objects that support the context management protocol such as those that have got the __enter__ and __exit__ methods.

What is a context manager Python?

A context manager is an object that defines a runtime context executing within the with statement.


1 Answers

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement.

The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally block). Some more explanation here.

A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):

class DatabaseConnection(object):      def __enter__(self):         # make a database connection and return it         ...         return self.dbconn      def __exit__(self, exc_type, exc_val, exc_tb):         # make sure the dbconnection gets closed         self.dbconn.close()         ... 

As explained above, use this object with the with statement (you may need to do from __future__ import with_statement at the top of the file if you're on Python 2.5).

with DatabaseConnection() as mydbconn:     # do stuff 

PEP343 -- The 'with' statement' has a nice writeup as well.

like image 148
ChristopheD Avatar answered Sep 18 '22 15:09

ChristopheD