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
try adding my answers (my thought of learning) :
__enter__
and[__exit__]
both are methods that are invoked on entry to and exit from the body of "the with statement" (PEP 343) and implementation of both is called context manager.the with statement is intend to hiding flow control of try finally clause and make the code inscrutable.
the syntax of the with statement is :
which translate to (as mention in PEP 343) :
try some code:
and now try manually (following translate syntax):
the result of the server side same as before
sorry for my bad english and my unclear explanations, thank you....
Using these magic methods (
__enter__
,__exit__
) allows you to implement objects which can be used easily with thewith
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):
As explained above, use this object with the
with
statement (you may need to dofrom __future__ import with_statement
at the top of the file if you're on Python 2.5).PEP343 -- The 'with' statement' has a nice writeup as well.
In addition to the above answers to exemplify invocation order, a simple run example
Produces the output:
A reminder: when using the syntax
with myclass() as mc
, variable mc gets the value returned by__enter__()
, in the above caseNone
! For such use, need to define return value, such as:If you know what context managers are then you need nothing more to understand
__enter__
and__exit__
magic methods. Lets see a very simple example.In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.
Now I am opening same file with with statement:
If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling
print(fp.closed)
attribute -- which returnsTrue
.This is because the file objects (fp in my example) returned by open function has two built-in methods
__enter__
and__exit__
. It is also known as context manager.__enter__
method is called at the start of with block and__exit__
method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have__enter__
and__exit__
methods. A class which implement both methods is known as context manager class.Now lets define our own context manager class.
I hope now you have basic understanding of both
__enter__
and__exit__
magic methods.I found it oddly difficult to locate the python docs for
__enter__
and__exit__
methods by Googling, so to help others here is the link:https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
I was hoping for a clear description of the
__exit__
method arguments. This is lacking but we can deduce them...Presumably
exc_type
is the class of the exception.It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?
We can answer by looking at this article:
http://effbot.org/zone/python-with-statement.htm
...so clearly
value
is an Exception instance.And presumably
traceback
is a Python traceback object.