<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged context-manager</title>
<link>https://coderlegion.com/tag/context-manager</link>
<description>Powered by Question2Answer</description>
<item>
<title> From Props to Context: Simplifying State Management in React </title>
<link>https://coderlegion.com/386/from-props-to-context-simplifying-state-management-in-react</link>
<description>&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Hey guys . Are u tired of passing of endless props and state variables to the child components while creating an application in React ? Well this post is just your ultimate saviour from that chaos. In this post I'll devlve into the uses of &lt;code&gt;useContext&lt;/code&gt; api in your react applications, which makes your work not only faster but a tad bit easy.&lt;/p&gt;
&lt;p&gt;Before diving into the details, I want to give you a visual aid that will act as the cherry on top of this blog! &lt;/p&gt;
&lt;p&gt;Okay, so first, imagine a store in your locality.  Now, this store in &lt;code&gt;useContext&lt;/code&gt; will be your &lt;code&gt;GlobalProvider&lt;/code&gt; component. Just as the store is only accessible to the people present in its locality, the &lt;code&gt;GlobalProvider&lt;/code&gt; component wraps the components we want to make the state data accessible to, essentially extending its &quot;locality&quot; to these specific components. ️&lt;/p&gt;
&lt;p&gt;This is just the gist of it all, and I know it seems a little confusing, but when we dive deep into the examples, things will get easier—trust me on this! &lt;/p&gt;
&lt;h3 id=&quot;creating-context&quot;&gt;Creating context&lt;/h3&gt;
&lt;p&gt;Now, the first step is to import the createContext function into our GlobalProvider component. This component will be our store , which will provide its items (state data) to its public (components). Let's take a look at it:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=11548114591033130575&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this code, we are creating a context using createContext and passing initialState, which consists of a string 'default value', to it. However, this value gets overridden by another value passed to the value prop of the &lt;code&gt;&amp;lt;GlobalState.Provider&amp;gt;&lt;/code&gt; component. This is actually our Provider component created from the context named &lt;code&gt;GlobalState&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;In simple terms, to provide our state data to any component, we need to wrap them with the Provider component created from the context name, like &lt;code&gt;GlobalState.Provider&lt;/code&gt; .&lt;/p&gt;
&lt;p&gt;In case you are wondering what the children prop of the &lt;code&gt;GlobalProvider&lt;/code&gt; component means here, it is actually a prop that is available to all components. It refers to any child component of the component using the &lt;code&gt;children&lt;/code&gt; prop.  So, it means that any component wrapped by the &lt;code&gt;GlobalProvider&lt;/code&gt; component will get access to the state variables. This is because we are wrapping the children of the &lt;code&gt;GlobalProvider&lt;/code&gt; component with the provider (GlobalState.Provider) of the state variables. &lt;br&gt;
If you wish to pass more than one value to all the components, you can do so by writing the values as an object in the &lt;code&gt;value&lt;/code&gt; prop like this: &lt;code&gt;value={{ firstValue: 'first value', secondValue: 'second value' }}&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;wrapping-components-by-wrapper-component&quot;&gt;Wrapping components by wrapper component&lt;/h3&gt;
&lt;p&gt;Before we move on to using the values in the components, we need to wrap the components with our wrapper component, which in this case is the GlobalProvider component.  Don't forget the concept of how in order for a person to get access to the items of a store, they need to be present in the store's locality.  This is how you would do that:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=10459000512157752527&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Also, keep in mind that whenever any of the values passed to the value prop changes, all the child components of the Provider component, the ones using the &lt;code&gt;useContext&lt;/code&gt; hook to extract the values, will re-render  whether they use the values in the jsx or not.&lt;/p&gt;
&lt;h3 id=&quot;using-usecontext-hook-to-access-state-data&quot;&gt;Using useContext hook to access state data&lt;/h3&gt;
&lt;p&gt;Finally, we can now use the values of our state using the &lt;code&gt;useContext&lt;/code&gt; hook of React. This hook expects a context, which in our case is &lt;code&gt;GlobalState&lt;/code&gt; (don't forget to export it from our &lt;code&gt;GlobalState.js&lt;/code&gt; file).&lt;/p&gt;
&lt;p&gt;First, let's take a look at the code :&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=12649371957215901018&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Here, we simply import the &lt;code&gt;useContext&lt;/code&gt; hook from React and pass &lt;code&gt;GlobalState&lt;/code&gt; (created using &lt;code&gt;createContext(initialState)&lt;/code&gt; imported from &lt;code&gt;GlobalState.js&lt;/code&gt;). Since in the last example we passed an object to the value prop of &lt;code&gt;GlobalState.Provider&lt;/code&gt;, we can now de-structure these values (&lt;code&gt;firstValue&lt;/code&gt; and &lt;code&gt;secondValue&lt;/code&gt;) from the object returned by &lt;code&gt;useContext&lt;/code&gt; hook. In simple terms, the &lt;code&gt;useContext&lt;/code&gt; hook returns the value defined in the value prop of the nearest Provider.&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;And there you have it!  I hope this blog has made the tedious process of passing state and props among components a breeze. By harnessing React's useContext and GlobalProvider, managing state becomes seamless and efficient. Now, with cleaner code and reduced complexity, you're ready to build more scalable and organized React applications. If you wish to put this knowledge to a test, then I would suggest making a simple expense tracker  in which you can do the following,&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Make a minimalist UI using multiple components like for one for showing the history of transactions, one for showing the total income , etc.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You can create one state variable in your globalProvider component which will then be shared among all the components so that you can use these values to update the balance as well as for recording the history of transactions and much more!&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Happy coding! ✨&lt;/p&gt;
</description>
<category>JavaScript</category>
<guid isPermaLink="true">https://coderlegion.com/386/from-props-to-context-simplifying-state-management-in-react</guid>
<pubDate>Sun, 07 Jul 2024 06:47:54 +0000</pubDate>
</item>
<item>
<title>Mastering Context Manager Simplifying Resource Management Python</title>
<link>https://coderlegion.com/361/mastering-context-manager-simplifying-resource-management-python</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;When working with resources in Python, we often perform &lt;strong&gt;repetitive tasks&lt;/strong&gt; such as setting up and closing processes, initializing something, &lt;strong&gt;opening and allocating resources, or closing it&lt;/strong&gt; to free up all the resources. However, we face a memory leak problem when the program retains the resources forever, even if they are no longer required. It compromises the system’s valuable resources. Therefore, all these tasks were &lt;strong&gt;automated using the context manager&lt;/strong&gt;. A &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/stdtypes.html#typecontextmanager&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;context manager&lt;/a&gt; makes it easier to &lt;strong&gt;allocate free resources&lt;/strong&gt; when working with files, setting up database connections, or managing network resources. It is important because efficient allocation and deallocation will &lt;strong&gt;prevent resource wastage&lt;/strong&gt; and maximize the use of available resources.&lt;br&gt; In this article, we discuss in detail how to achieve the maximum use of resources through context manager, its significance, and working with other Python modules.&lt;/p&gt;
&lt;h2 style=&quot;margin: 02;&quot;&gt;Understanding Context Manager&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0 0 0 0;&quot;&gt;1. Explanation Of What Context Manager Is And Why It Is Useful&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0 margin-bottom: 0;&quot;&gt;The context manager allows us to properly manage resources so that we can specify exactly what we want to &lt;strong&gt;set up and tear down&lt;/strong&gt; when working with certain objects, such as file handling or database connections. It sets up a temporary runtime context for you and destroys the context after all operations are completed. In Python, context manager play a vital role in resource management by providing a convenient way to acquire and release resources within the context. It is widely performed using the &quot;with&quot; keyword. It makes sure that the application will not undergo crashes by properly handling resources.&lt;/p&gt; 
&lt;h3 style=&quot;margin-top: 0; margin-bottom: 0;&quot;&gt;2. Introduction To The &quot;with&quot; Statement As The Primary Way To Use Context Manager In Python&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;The &quot;with&quot; statement is a built-in module of Python that is used to streamline the management of resources. It assures that the required external resources are properly handled and cleaned up after use, even if an exception occurs during execution. It is favored mostly when dealing with files, network or database connections, or any other kind of resource that needs to be properly handled.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0;&quot;&gt;3. Overview Of The &quot;contextlib&quot; Module For Creating Context Manager&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 0;&quot;&gt;As we explore the realm of context manager, it is imperative to grasp the significance of the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/contextlib.html&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt; &quot;contextlib&quot;&lt;/a&gt; module. This is a fundamental module that provides utilities for creating and working with the context management function and &quot;with&quot; statements by providing more control over resource management. It is a part of the Python standard library and offers various functions to work with the context manager. For instance, it includes the &lt;strong&gt;&quot;contextmanager&quot;&lt;/strong&gt; decorator that allows you to define the context manager using generators. Also, the &lt;strong&gt;&quot;closing()&quot;&lt;/strong&gt; function creates the context manager of the specified object and closes it when it leaves the context to handle resources properly. Thus, it is a handy Python module that allows a concise way of dealing with a context manager or &quot;with&quot; statements.&lt;/p&gt;  
&lt;h2 style=&quot;margin: 0;&quot;&gt;Using Context Manager With The &quot;with&quot; Statement&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;1. Demonstration of Using Built-in Context Manager With The &quot;with&quot; Statement&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;The &quot;with&quot; statement contains many built-in context manager functions that wrap the execution of the block of code within the specified context. The first is the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/199/python-writing-to-files&quot; target=&quot;_blank&quot;&gt;open&lt;/a&gt; function, which is used to perform file I/O operations. By using the context manager in the program, we ensure that the allocated resources are released, and the file is closed correctly. This will help us reduce the deadlock condition and resource wastage. You can perform this by opening the file using the &quot;with&quot; keyword.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;file_path = &quot;Context.txt&quot;   #provides file location
with open(file_path, 'r') as file:   #context manager having file path and its opening mode
    file_content = file.read()  #this will read the file and save the file into file_content object
    print(&quot;The Content of file is:&quot;)
    print(file_content)
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0.4;&quot;&gt;In this example, the “with” statement is used to open a file named &quot;Context.txt&quot;. The file is automatically closed after it is read, even if an exception occurs during the reading process. We do not have to explicitly mention close() because the “with” statement will close the file properly and release the resources, thereby preventing any potential resource leak.&lt;/p&gt;
&lt;h3 style=&quot;margin-top: 0.5;&quot;&gt;2. Context Manager Protocol And The __enter__() And __exit__() Methods&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Python has defined some context management protocols that dictate how an object can act as a context manager by implementing the __enter__() and __exit__() methods. Any class, function, or object that implements these methods according to the protocols would act as a context manager. These methods are defined as follows:&lt;/p&gt;
&lt;ol&gt; 
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;__enter__(): It is called by the &quot;with&quot; statement &lt;strong&gt;to set up any resources&lt;/strong&gt; or state required by the context manager to function.&lt;/li&gt; 
&lt;li style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;__exit__(): It is called right before leaving the &quot;with&quot; statement &lt;strong&gt;to handle the cleanup operations.&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;When the &quot;with&quot; statement executes, the expression within it is evaluated and creates the context manager (a resulting value e.g. object of the file), and Python calls the __enter__() methods to assign the return value to the variable given by &quot;as&quot;. Then, the __exist__() method is called on the context manager object to release the allocated resources.&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Remember that the double underscore methods are special methods that are not called but triggered. They are internally set to run at specific times or after certain events.&lt;/span&gt; 
&lt;/div&gt; 
&lt;h3 style=&quot;margin-top: 0; margin-bottom: 0.3;&quot;&gt;Example Of Implementing A Custom Context Manager Using A Class&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0.4; margin-bottom: 0;&quot;&gt;Let's understand the __enter__() and __exit__() methods by implementing a custom context manager using a class.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;class File:
    def __init__(self, filename, mode): #initilize the class object with file name and mode
        self.filename = filename
        self.mode = mode

    def __enter__(self): #initilize the __enter__ method for opening the file
        print(f&quot;Opening {self.filename} .......&quot;)
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_value, traceback): # initilize the __exit__ method for closing the file
        print(f&quot;Closing {self.filename} ......&quot;)
        self.file.close()

#using the custom context manager
with File('Context.txt', 'r') as file:
    content = file.read()
    print(content)
    print(&quot;Done!&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11856599318032258096&quot; alt=&quot;&quot;&gt;&lt;br&gt;
 &lt;br&gt;
&lt;/p&gt;&lt;h2 style=&quot;margin-top: 0; margin-bottom:0;&quot;&gt;Context Manager With The &quot;contextlib&quot; Module&lt;/h2&gt; &lt;br&gt;
&lt;h3 style=&quot;margin: 0;&quot;&gt;1. &quot;contextlib&quot; Module And Its Utilities For Creating Context Manager&lt;/h3&gt; &lt;br&gt;
&lt;p style=&quot;text-align: justify; margin: 0;&quot;&gt;The &quot;contextlib&quot; module provides utilities for common tasks involving the Python &quot;with&quot; statement. It provides a decorator &quot;contextmanager&quot; that allows us a simple way to manage resources and perform setup/teardown operations. This module provides a convenient way to deal with context manager. It is implemented according to the &lt;strong&gt;context manager protocols&lt;/strong&gt;. This is useful when dealing with operations that require resource management, including &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/186/python-opening-%26-reading-files&quot; target=&quot;_blank&quot;&gt;file handling&lt;/a&gt; and database connections for acquiring and releasing locks.&lt;/p&gt; &lt;br&gt;
&lt;h3 style=&quot;margin: 0;&quot;&gt;2. Illustration Of Using The &quot;contextmanager&quot; Decorator To Create Context Manager As Generator Function&lt;/h3&gt; &lt;br&gt;
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0.4;&quot;&gt;The &quot;contextmanager&quot; is the decorator of the &quot;contextlib&quot; module, which turns the generator function into a context manager. It is defined using the &lt;strong&gt;&quot;@&quot;&lt;/strong&gt; keyword. It contains the yield value that acts as the required resource. The block of code before the yield value is the setup block to enter the &quot;with&quot; statement, while the code after the yield value is called the teardown block to clean up the resources. Let's understand this with the help of the file opening and reading the Python example.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from contextlib import contextmanager #import library

@contextmanager #decorator on generator function making it context manager
def file(filename, mode):  #before yielding, it acts as the enter function
  print(&quot;This is the implicit ENTER block&quot;)
  my_file = open(filename, mode)

  yield my_file #yielding the with statement to open the file
  
  print(&quot;This is the implicit EXIT block&quot;) #after yielding, it acts as exit function
  my_file.close()

with file(&quot;Context.txt&quot;, 'r') as file_content: #operating for opening the file
   content = file_content.read()
   print(content)
   print(&quot;I'm in WITH block&quot;)
   pass
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=8095794674607915625&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0;&quot;&gt;3. Example Of Creating A Context Manager For Timer Context Manager Using The &quot;contextmanager&quot; Decorator&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 0;&quot;&gt;Let's take another example of using the 'contextmanager' decorator for implementing timer code execution of context manager. The timer context manager is going to tell us how long a bunch of statements took to execute that were within the 'with' statement. &lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;from contextlib import contextmanager
from datetime import datetime
from time import sleep

@contextmanager #context manager decorator
def timer(): #function to calculate the time taken by each line in with statement
    start = datetime.now()
    yield
    print(f&quot;Time Taken {(datetime.now() - start).seconds} second&quot;)

def timer_test(): #for testing the function
    with timer():
        sleep(2)

timer_test() #calling the function
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7979072388036584235&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 0;&quot;&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; In the above code, I use three libraries: the first is for creating a context manager, the second is for obtaining the current datetime for calculation, and the last is for making the process pause for 2 seconds.  This means that this code measures the time taken by the “with” statement code. Therefore, to test this, we paused the execution of the “with” statement for 2 s. &lt;/p&gt; 
&lt;h2 style=&quot;margin-top: 0; margin-bottom: 0.5;&quot;&gt;Handling Exceptions With Context Manager&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0;&quot;&gt;1. How Context Manager Handle Exceptions And Ensure Resource Cleanup &lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 0;&quot;&gt;Python streamlines &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/164/python-try-except-blocks&quot; target=&quot;_blank&quot; title=&quot;Exception handling&quot;&gt;&lt;strong&gt;exception handling&lt;/strong&gt;&lt;/a&gt; using the context manager and the &quot;with&quot; statement. We know that exceptions are errors that deviate the program from its normal flow. We need exception handling to handle them gracefully. However, the &quot;with&quot; statement in Python performs exception handling by following the context manager protocols. This ensures that the required setup and teardown process is properly managed even if an exception occurs. It assures the proper management of program resources and executes the necessary &quot;cleanup&quot; actions, regardless of the occurrence of an exception. &lt;/p&gt; 
&lt;h3 style=&quot;margin-top: 0;&quot;&gt;2. Illustration Of Using Context Manager To Safely Manage Resources In The Presence Of Exceptions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0;&quot;&gt;By utilizing the context manager in the program, we can handle exceptions beforehand while coding the application as well as manage the resources. It is important to use the &quot;with&quot; statement when working with file operations to handle potential exceptions gracefully related to FileNotFound or FileExist errors. So, let's discuss the example of a CSV file where an exception can occur and cause the program to crash and abruptly stop. &lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;import csv #importing the csv module
file_path = &quot;Sample-CSV.csv&quot; #provide location of file in the same directory        
try:
    #use the context manager for closing the file
    with open(file_path, 'r', encoding='utf-8') as file: #here, the file open operation is performed with read mode    
       csv_content = csv.reader(file) #read the file using csvreader function and save it into variable
       for record in csv_content: #iterate through the rows
         print(record) #print the record 
except FileNotFoundError as e: #if file not found  
  print(&quot;Provide correct File Path&quot;) 
except UnicodeDecodeError as e: #if incorrect encoding scheme used to decode  
  print(&quot;Cannot decode the file&quot;)   
else:  
  print(&quot;No exception found&quot;)  
finally:   
  print(&quot;END of With statement&quot;) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10846614728946537964&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin-bottom: 0; margin-top: 0&quot;&gt;3. Example Of Implementing Exception Handling Logic In A Custom Context Manager&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin-top: 0; margin-bottom: 0&quot;&gt;Instead of using the &quot;with&quot; statement for exception handling, we can also create our custom-based context manager that manages the resources and gracefully handles the exception. So, let's create a simple custom context manager.&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;class FileWriter:
    def __init__(self, filename, mode): #initilize the class object with file name and mode
        self.filename = filename
        self.mode = mode

    def __enter__(self): #initilize the __enter__ method for opening the file
        print(f&quot;Opening {self.filename} .......&quot;)
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_value, traceback): # initilize the __exit__ method for closing the file
        print(f&quot;Closing {self.filename} ......&quot;)
        self.file.close()
        if exc_type is not None:
            print(f&quot;An Error Occured: {exc_value}&quot;) #Intentionally raised exception.
        return True

#using the custom context manager
with FileWriter('Context.txt', 'w') as file:
    file.write(f&quot;Lots of help: Many tools to make different kinds of programs.&quot;)
    raise Exception(&quot;Test exception - this will be suppressed.&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13262774670183066696&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;'exc_type' is the exception class, such as AttributeError and IndexError. 'exc_value' is the exception instance with the message. 'traceback' is the full traceback of the error. 
&lt;/span&gt; 
&lt;/div&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the above code, the __enter__() method opens the file name &quot;Context.txt&quot; in writing mode. It returns the file object that would be used to operate within the &quot;with&quot; block. After that, the __exit__() method is called, which ensures that the resources are closed and not left open. Then, it checks for the exception occurrence at this line &lt;strong&gt;&quot;exc_type is not None&quot;&lt;/strong&gt; which verifies whether the exception type is passed to the exit method of the context manager. Here, I am explicitly raising the exception to explain this in a better way. Then, upon obtaining the exception information, it attempts to surpass the exception with &quot;return True&quot; to manage the resources in case the exception occurs.&lt;/p&gt;
&lt;div class=&quot;div-red&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Warning:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Be cautious while raising exceptions within context manager when working in real-world scenarios, as it can impact the control flow and execution of the program.
&lt;/span&gt; 
&lt;/div&gt; 
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 5px; margin-top: 2px;&quot;&gt;
  &lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: #333;&quot;&gt;FAQs&lt;/span&gt;
  &lt;div class=&quot;faq-body&quot; style=&quot;margin-top: 2px; margin-bottom: 10px;&quot;&gt;
    &lt;strong&gt;Q:&lt;/strong&gt; Why are context manager used in Python&lt;br&gt;
    &lt;strong&gt;A:&lt;/strong&gt; Context manager is used to handle setup and teardown actions in a convenient manner hoping that all the resources are properly managed and released regardless of exception occurrence.
  &lt;/div&gt;
  &lt;div class=&quot;faq-body&quot; style=&quot;margin-top: 2px; margin-bottom: 10px;&quot;&gt;
    &lt;strong&gt;Q:&lt;/strong&gt; How do you create a context manager using classes?&lt;br&gt;
    &lt;strong&gt;A:&lt;/strong&gt; You can create the custom context manager by implementing the context manager protocols which include two methods: __enter__() and __exit__().
  &lt;/div&gt;
  &lt;div class=&quot;faq-body&quot; style=&quot;margin-top: 2px; margin-bottom: 10px;&quot;&gt;
    &lt;strong&gt;Q:&lt;/strong&gt; How to implement context manager using contextlib library?&lt;br&gt;
    &lt;strong&gt;A:&lt;/strong&gt;The &quot;contextmanager&quot; decorator is used to implement the function as a context manager,  just like the generator function.
  &lt;/div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In conclusion, we have seen how the context manager provides a &lt;strong&gt;concise and structured approach&lt;/strong&gt; to managing resources within the &quot;with&quot; statement. It promotes the allocation and deallocation of resources in a well-organized manner. In addition, to try-finally block the clean-up task, we can efficiently manage the resources using the Python built-in feature i.e.  &lt;strong&gt;&quot;with&quot; statement&lt;/strong&gt;. We start with the basic concept, including the predefined way of using it, and move toward the &lt;strong&gt;custom-based context manager&lt;/strong&gt;, which we can create using the class and the contextlib library. We also learned how to use it to deal with exceptions and abnormal behavior in the program. As a junior developer, understanding and grasping this concept will level up you're coding and resource management skills. I hope this guide has given you a basic knowledge of the context manager. Thank You for reading this guide. Happy Coding! &lt;/p&gt; 
&lt;hr&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Additonal Resources&lt;/h2&gt;   
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/contextlib.html&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;Official &quot;contextlib&quot; module documentation&lt;/a&gt; provide tools for creating and managing context manager.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#the-with-statement&quot; title=&quot;file&quot; target=&quot;_blank&quot;&gt;Official &quot;with&quot; statement documentation&lt;/a&gt;  offers its fundamentals and more usage in Python program.&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Adv Concepts</category>
<guid isPermaLink="true">https://coderlegion.com/361/mastering-context-manager-simplifying-resource-management-python</guid>
<pubDate>Sun, 16 Jun 2024 04:05:15 +0000</pubDate>
</item>
</channel>
</rss>