{"id":1215,"date":"2020-11-20T03:29:37","date_gmt":"2020-11-20T03:29:37","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1215"},"modified":"2022-05-16T07:00:22","modified_gmt":"2022-05-16T07:00:22","slug":"python-context-managers","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/advanced-python\/python-context-managers\/","title":{"rendered":"Python Context Managers"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the Python context managers and how to use them effectively <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-python-context-managers'>Introduction to Python context managers <a href=\"#introduction-to-python-context-managers\" class=\"anchor\" id=\"introduction-to-python-context-managers\" title=\"Anchor for Introduction to Python context managers\">#<\/a><\/h2>\n\n\n\n<p>A <strong>context manager<\/strong> is an <strong>object<\/strong> that defines a <strong>runtime context<\/strong> executing within the <code>with<\/code> statement.<\/p>\n\n\n\n<p>Let&#8217;s start with a simple example to understand the context manager concept.<\/p>\n\n\n\n<p>Suppose that you have a file called <code>data.txt<\/code> that contains an <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-integers\/\">integer<\/a> <code>100<\/code>.<\/p>\n\n\n\n<p>The following program <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-read-text-file\/\">reads<\/a> the <code>data.txt<\/code> file, converts its contents to a number, and shows the result to the standard output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">f = open(<span class=\"hljs-string\">'data.txt'<\/span>)\ndata = f.readlines()\n\n<span class=\"hljs-comment\"># convert the number to integer and display it<\/span>\nprint(int(data&#91;<span class=\"hljs-number\">0<\/span>]))\n\nf.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The code is simple and straightforward. <\/p>\n\n\n\n<p>However, the <code>data.txt<\/code> may contain data that cannot be converted to a number. In this case, the code will result in an exception.<\/p>\n\n\n\n<p>For example, if the <code>data.txt<\/code> contains the string <code>'100'<\/code> instead of the number 100, you&#8217;ll get the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">ValueError: invalid literal <span class=\"hljs-keyword\">for<\/span> int() <span class=\"hljs-keyword\">with<\/span> base <span class=\"hljs-number\">10<\/span>: <span class=\"hljs-string\">\"'100'\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Because of this exception, Python may not close the file properly.<\/p>\n\n\n\n<p>To fix this, you may use the <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except-finally\/\"><code>try...except...finally<\/code> <\/a>statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    f = open(<span class=\"hljs-string\">'data.txt'<\/span>)\n    data = f.readlines()\n    <span class=\"hljs-comment\"># convert the number to integer and display it<\/span>\n    print(int(data&#91;<span class=\"hljs-number\">0<\/span>]))\n<span class=\"hljs-keyword\">except<\/span> ValueError <span class=\"hljs-keyword\">as<\/span> error:\n    print(error)\n<span class=\"hljs-keyword\">finally<\/span>:\n    f.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Since the code in the <code>finally<\/code> block always executes, the code will always close the file properly.<\/p>\n\n\n\n<p>This solution works as expected. However, it&#8217;s quite verbose.<\/p>\n\n\n\n<p>Therefore, Python provides you with a better way that allows you to automatically close the file after you complete processing it.<\/p>\n\n\n\n<p>This is where <strong>context managers <\/strong>come into play.<\/p>\n\n\n\n<p>The following shows how to use a context manager to process the <code>data.txt<\/code> file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">'data.txt'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    data = f.readlines()\n    print(int(data&#91;<span class=\"hljs-number\">0<\/span>])    \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we use the <code>open()<\/code> function with the <code>with<\/code> statement. After the <code>with<\/code> block, Python will close automatically.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-with-statement'>Python with statement <a href=\"#python-with-statement\" class=\"anchor\" id=\"python-with-statement\" title=\"Anchor for Python &lt;code&gt;with&lt;\/code&gt; statement\">#<\/a><\/h2>\n\n\n\n<p>Here is the typical syntax of the <code>with<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> context <span class=\"hljs-keyword\">as<\/span> ctx:\n    <span class=\"hljs-comment\"># use the the object <\/span>\n\n<span class=\"hljs-comment\"># context is cleaned up<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>When Python encounters the <code>with<\/code> statement, it creates a new context. The context can optionally return an <code>object<\/code>.<\/li><li>After the <code>with<\/code> block, Python cleans up the context automatically.<\/li><li>The scope of the <code>ctx<\/code> has the same scope as the <code>with<\/code> statement. It means that you can access the <code>ctx<\/code> both inside and after the <code>with<\/code> statement.<\/li><\/ul>\n\n\n\n<p>The following shows how to access the <code>f<\/code> variable after the <code>with<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> open(<span class=\"hljs-string\">'data.txt'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    data = f.readlines()\n    print(int(data&#91;<span class=\"hljs-number\">0<\/span>]))\n\n\nprint(f.closed)  <span class=\"hljs-comment\"># True<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='python-context-manager-protocol'>Python context manager protocol <a href=\"#python-context-manager-protocol\" class=\"anchor\" id=\"python-context-manager-protocol\" title=\"Anchor for Python context manager protocol\">#<\/a><\/h2>\n\n\n\n<p>Python context managers work based on the <strong>context manager protocol<\/strong>.<\/p>\n\n\n\n<p>The context manager protocol has the following methods:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>__enter__()<\/code> &#8211; setup the context and optionally return some object<\/li><li><code>__exit__()<\/code> &#8211; cleanup the object.<\/li><\/ul>\n\n\n\n<p>If you want a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">class<\/a> to support the context manager protocol, you need to implement these two methods.<\/p>\n\n\n\n<p>Suppose that <code>ContextManager<\/code> is a class that supports the context manager protocol.<\/p>\n\n\n\n<p>The following shows how to use the <code>ContextManager<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">with<\/span> ContextManager() <span class=\"hljs-keyword\">as<\/span> ctx:\n    <span class=\"hljs-comment\"># do something<\/span>\n<span class=\"hljs-comment\"># done with the context<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When you use <code>ContextManager<\/code> class with the <code>with<\/code> statement, Python implicitly creates an instance of the <code>ContextManager<\/code> class (<code>instance<\/code>) and automatically call <code>__enter__()<\/code> method on that instance.<\/p>\n\n\n\n<p>The <code>__enter__()<\/code> method may optionally return an object. If so, Python assigns the returned object the <code>ctx<\/code>.<\/p>\n\n\n\n<p>Notice that <code>ctx<\/code> references the object returned by the <code>__enter__()<\/code> method. It doesn&#8217;t reference the instance of the <code>ContextManager<\/code> class.<\/p>\n\n\n\n<p>If an exception occurs inside the with block or after the <code>with<\/code> block, Python calls the <code>__exit__()<\/code> method on the <code>instance<\/code> object.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"456\" height=\"415\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Context-Manager.png\" alt=\"Python Context Managers\" class=\"wp-image-1224\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Context-Manager.png 456w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/11\/Python-Context-Manager-300x273.png 300w\" sizes=\"auto, (max-width: 456px) 100vw, 456px\" \/><\/figure>\n\n\n\n<p>Functionally, the <code>with<\/code> statement is equivalent to the following <code>try...finally<\/code> statement:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">   instance = ContextManager()\nctx = instance.__enter__()\n\n<span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># do something with the txt<\/span>\n<span class=\"hljs-keyword\">finally<\/span>:\n    <span class=\"hljs-comment\"># done with the context<\/span>\n    instance.__exit__()\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id='the-__enter__-method'>The __enter__() method <a href=\"#the-__enter__-method\" class=\"anchor\" id=\"the-__enter__-method\" title=\"Anchor for The __enter__() method\">#<\/a><\/h3>\n\n\n\n<p>In the <code>__enter__()<\/code> method, you can carry the necessary steps to setup the context. <\/p>\n\n\n\n<p>Optionally, you can returns an object from the <code>__enter__()<\/code> method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='the-__exit__-method'>The __exit__() method <a href=\"#the-__exit__-method\" class=\"anchor\" id=\"the-__exit__-method\" title=\"Anchor for The __exit__() method\">#<\/a><\/h3>\n\n\n\n<p>Python always executes the <code>__exit__()<\/code> method even if an exception occurs in the <code>with<\/code> block.<\/p>\n\n\n\n<p>The <code>__exit__()<\/code> method accepts three arguments: exception type, exception value, and traceback object. All of these arguments will be <code>None<\/code> if no exception occurs.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__exit__<\/span><span class=\"hljs-params\">(self, ex_type, ex_value, ex_traceback)<\/span>:<\/span>\n    ...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>__exit__()<\/code> method returns a boolean value, either <code>True<\/code> or <code>False<\/code>.<\/p>\n\n\n\n<p>If the return value is True, Python will make any exception silent. Otherwise, it doesn&#8217;t silence the exception.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-context-manager-applications'>Python context manager applications <a href=\"#python-context-manager-applications\" class=\"anchor\" id=\"python-context-manager-applications\" title=\"Anchor for Python context manager applications\">#<\/a><\/h2>\n\n\n\n<p>As you see from the previous example, the common usage of a context manager is to open and close files automatically.<\/p>\n\n\n\n<p>However, you can use context managers in many other cases:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='1-open-close'>1) Open &#8211; Close <a href=\"#1-open-close\" class=\"anchor\" id=\"1-open-close\" title=\"Anchor for 1) Open - Close\">#<\/a><\/h3>\n\n\n\n<p>If you want to open and close a resource automatically, you can use a context manager.<\/p>\n\n\n\n<p>For example, you can open a socket and close it using a context manager.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='2-lock-release'>2) Lock &#8211; release <a href=\"#2-lock-release\" class=\"anchor\" id=\"2-lock-release\" title=\"Anchor for 2) Lock - release\">#<\/a><\/h3>\n\n\n\n<p>Context managers can help you manage locks for objects more effectively. They allow you to acquire a lock and release it automatically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='3-start-stop'>3) Start &#8211; stop <a href=\"#3-start-stop\" class=\"anchor\" id=\"3-start-stop\" title=\"Anchor for 3) Start - stop\">#<\/a><\/h3>\n\n\n\n<p>Context managers also help you to work with a scenario that requires the start and stop phases.<\/p>\n\n\n\n<p>For example, you can use a context manager to start a timer and stop it automatically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='3-change-reset'>3) Change &#8211; reset <a href=\"#3-change-reset\" class=\"anchor\" id=\"3-change-reset\" title=\"Anchor for 3) Change - reset\">#<\/a><\/h3>\n\n\n\n<p>Context managers can work with change and reset scenario. <\/p>\n\n\n\n<p>For example, your application needs to connect to multiple data sources. And it has a default connection.<\/p>\n\n\n\n<p>To connect to another data source:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>First, use a context manager to change the default connection to a new one. <\/li><li>Second, work with the new connection<\/li><li>Third, reset it back to the default connection once you complete working with the new connection.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='implementing-python-context-manager-protocol'>Implementing Python context manager protocol <a href=\"#implementing-python-context-manager-protocol\" class=\"anchor\" id=\"implementing-python-context-manager-protocol\" title=\"Anchor for Implementing Python context manager protocol\">#<\/a><\/h2>\n\n\n\n<p>The following shows a simple implementation of the <code>open()<\/code> function using the context manager protocol:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">File<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, filename, mode)<\/span>:<\/span>\n        self.filename = filename\n        self.mode = mode\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__enter__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        print(<span class=\"hljs-string\">f'Opening the file <span class=\"hljs-subst\">{self.filename}<\/span>.'<\/span>)\n        self.__file = open(self.filename, self.mode)\n        <span class=\"hljs-keyword\">return<\/span> self.__file\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__exit__<\/span><span class=\"hljs-params\">(self, exc_type, exc_value, exc_traceback)<\/span>:<\/span>\n        print(<span class=\"hljs-string\">f'Closing the file <span class=\"hljs-subst\">{self.filename}<\/span>.'<\/span>)\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> self.__file.closed:\n            self.__file.close()\n\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-literal\">False<\/span>\n\n\n<span class=\"hljs-keyword\">with<\/span> File(<span class=\"hljs-string\">'data.txt'<\/span>, <span class=\"hljs-string\">'r'<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    print(int(next(f)))\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>First, initialize the <code>filename<\/code> and <code>mode<\/code> in the <code>__init__()<\/code> method.<\/li><li>Second, open the file in the <code>__enter__()<\/code> method and return the file object.<\/li><li>Third, close the file if it&#8217;s open in the <code>__exit__()<\/code> method.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='using-python-context-manager-to-implement-the-start-and-stop-pattern'>Using Python context manager to implement the start and stop pattern <a href=\"#using-python-context-manager-to-implement-the-start-and-stop-pattern\" class=\"anchor\" id=\"using-python-context-manager-to-implement-the-start-and-stop-pattern\" title=\"Anchor for Using Python context manager to implement the start and stop pattern\">#<\/a><\/h2>\n\n\n\n<p>The following defines a <code>Timer<\/code> class that supports the context manager protocol:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> time <span class=\"hljs-keyword\">import<\/span> perf_counter\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Timer<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        self.elapsed = <span class=\"hljs-number\">0<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__enter__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        self.start = perf_counter()\n        <span class=\"hljs-keyword\">return<\/span> self\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__exit__<\/span><span class=\"hljs-params\">(self, exc_type, exc_value, exc_traceback)<\/span>:<\/span>\n        self.stop = perf_counter()\n        self.elapsed = self.stop - self.start\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-literal\">False<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>First, import the <code>perf_counter<\/code> from the <code>time<\/code> module.<\/li><li>Second, start the timer in the <code>__enter__()<\/code> method<\/li><li>Third, stop the timer in the <code>__exit__()<\/code> method and return the elapsed time.<\/li><\/ul>\n\n\n\n<p>Now, you can use the <code>Timer<\/code> class to measure the time needed to calculate the Fibonacci of 1000, one million times:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">fibonacci<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    f1 = <span class=\"hljs-number\">1<\/span>\n    f2 = <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">for<\/span> i <span class=\"hljs-keyword\">in<\/span> range(n<span class=\"hljs-number\">-1<\/span>):\n        f1, f2 = f2, f1 + f2\n\n    <span class=\"hljs-keyword\">return<\/span> f1\n\n\n<span class=\"hljs-keyword\">with<\/span> Timer() <span class=\"hljs-keyword\">as<\/span> timer:\n    <span class=\"hljs-keyword\">for<\/span> _ <span class=\"hljs-keyword\">in<\/span> range(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">1000000<\/span>):\n        fibonacci(<span class=\"hljs-number\">1000<\/span>)\n\nprint(timer.elapsed)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use Python context managers to define runtime contexts when executing in the <code>with<\/code> statement.<\/li><li>implement the <code>__enter__()<\/code> and <code>__exit__()<\/code> methods to support the context manager protocol.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1215\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-context-managers\/\"\n\t\t\t\tdata-post-title=\"Python Context Managers\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1215\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-context-managers\/\"\n\t\t\t\tdata-post-title=\"Python Context Managers\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about the Python context managers and how to use them effectively.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":757,"menu_order":23,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1215","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1215","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=1215"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1215\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/757"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=1215"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}