@@ -7,7 +7,7 @@ the ``with`` statement. Suppose you have two related operations which
77you’d like to execute as a pair, with a block of code in between.
88Context managers allow you to do specifically that. For example:
99
10- ::
10+ .. code :: python
1111
1212 with open (' some_file' , ' w' ) as opened_file:
1313 opened_file.write(' Hola!' )
@@ -16,7 +16,7 @@ The above code opens the file, writes some data to it and then closes
1616it. If an error occurs while writing the data to the file, it tries to
1717close it. The above code is equivalent to:
1818
19- ::
19+ .. code :: python
2020
2121 file = open (' some_file' , ' w' )
2222 try :
@@ -42,7 +42,7 @@ At the very least a context manager has an ``__enter__`` and
4242``__exit__ `` methods defined. Let's make our own file opening Context
4343Manager and learn the basics.
4444
45- ::
45+ .. code :: python
4646
4747 class File (object ):
4848 def __init__ (self , file_name , method ):
@@ -55,7 +55,7 @@ Manager and learn the basics.
5555 Just by defining ``__enter__ `` and ``__exit__ `` methods we can use it in
5656a ``with `` statement. Let's try:
5757
58- ::
58+ .. code :: python
5959
6060 with File(' demo.txt' , ' w' ) as opened_file:
6161 opened_file.write(' Hola!' )
@@ -87,7 +87,7 @@ What if our file object raises an exception? We might be trying to
8787access a method on the file object which it does not supports. For
8888instance:
8989
90- ::
90+ .. code :: python
9191
9292 with File(' demo.txt' , ' w' ) as opened_file:
9393 opened_file.undefined_function(' Hola!' )
@@ -107,15 +107,15 @@ In our case the ``__exit__`` method returns ``None`` (when no return
107107statement is encountered then the method returns ``None ``). Therefore,
108108``with `` statement raises the exception.
109109
110- ::
110+ .. code :: python
111111
112112 Traceback (most recent call last):
113113 File " <stdin>" , line 2 , in < module>
114114 AttributeError : ' file' object has no attribute ' undefined_function'
115115
116116 Let's try handling the exception in the ``__exit__ `` method:
117117
118- ::
118+ .. code :: python
119119
120120 class File (object ):
121121 def __init__ (self , file_name , method ):
@@ -146,7 +146,7 @@ Python has a contextlib module for this very purpose. Instead of a
146146class, we can implement a Context Manager using a generator function.
147147Let's see a basic, useless example:
148148
149- ::
149+ .. code :: python
150150
151151 from contextlib import contextmanager
152152
@@ -177,7 +177,7 @@ Let's disect this method a little.
177177So now that we know all this, we can use the newly generated Context
178178Manager like this:
179179
180- ::
180+ .. code :: python
181181
182182 with open_file(' some_file' ) as f:
183183 f.write(' hola!' )
0 commit comments