<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jai Kishan on Medium]]></title>
        <description><![CDATA[Stories by Jai Kishan on Medium]]></description>
        <link>https://medium.com/@jkishan421?source=rss-7431ddbc3d22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0bRESKyu3y4R4IYDCfpE2A.jpeg</url>
            <title>Stories by Jai Kishan on Medium</title>
            <link>https://medium.com/@jkishan421?source=rss-7431ddbc3d22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:25:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jkishan421/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Builder Pattern in Python: Clean Code for Complex Object Creation]]></title>
            <link>https://medium.com/@jkishan421/builder-pattern-in-python-clean-code-for-complex-object-creation-bb33afff18ff?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb33afff18ff</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 21:11:52 GMT</pubDate>
            <atom:updated>2025-07-29T21:11:52.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*J3k3_Qgs8wK95yIH.png" /></figure><p>When working with Python (or any object-oriented language), we often encounter situations where creating an object with multiple optional fields becomes messy and hard to manage. This is where <strong>design patterns</strong> shine, especially the <strong>Builder Pattern</strong>, which helps us tackle the problem of constructing complex objects cleanly and step-by-step.</p><p>In this article, we’ll explore the <strong>Builder Pattern</strong>, a powerful and elegant solution for assembling objects with numerous attributes, while maintaining readability, flexibility, and maintainability in your code.</p><h3>What is Builder Pattern?</h3><p>The <strong>Builder Pattern</strong> is a <strong>creational design pattern</strong> used to construct <strong>complex objects step by step</strong>. It allows you to <strong>create different representations of an object</strong> using the same construction process.</p><h3>Why Use it?</h3><ul><li>When an object has <strong>many optional parameters</strong> or <strong>complex construction</strong>.</li><li>To <strong>decouple the construction logic</strong> from the representation.</li><li>To <strong>avoid long, unreadable constructors</strong> (a.k.a. constructor pollution).</li><li>To ensure <strong>immutability</strong> or to <strong>avoid constructor pollution</strong>.</li></ul><h3>Problem Scenario (Without Builder):</h3><p>Imagine you want to create a Computer object, but it has many optional parts: CPU, GPU, RAM, storage, keyboard, monitor, etc.</p><p>You might end up with something like this:</p><h4>Using Constructor with Many Arguments</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d50b6cb5107c27b54a771e909d294a43/href">https://medium.com/media/d50b6cb5107c27b54a771e909d294a43/href</a></iframe><h4>Issues:</h4><ol><li>Hard to <strong>remember the order</strong> of parameters.</li><li>Optional values become confusing (which are None?).</li><li><strong>Hard to maintain</strong> or extend (e.g., what if you add OS later?).</li><li>Constructor becomes long and unreadable.</li></ol><h3>Solution: The Builder Pattern</h3><p>Instead of stuffing everything into one constructor, we <strong>build the object step-by-step</strong> using method chaining:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76f9ebf176e15dde3101958f670b658/href">https://medium.com/media/a76f9ebf176e15dde3101958f670b658/href</a></iframe><p>In this example we created a class of our Entity (Computer) and create another class to build the Entity (ComputerBuilder). In our main method we make an object of builder and construct our pc.</p><h4>Benefits:</h4><ol><li>Clear, readable method chaining</li><li>Only set what you need</li><li>Can add validations in builder methods</li><li>Changes are localized to builder</li></ol><h3>Real-World Example: Matplotlib</h3><p>If you’ve used <strong>Matplotlib</strong>, you’ve already experienced the Builder Pattern in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIaGDfmcqc7AARKE6bb1cA.png" /></figure><p>Each step, creating a figure, setting labels, adding data, is built up in layers. This is a <strong>builder-like approach</strong> that makes plotting <strong>modular, readable, and composable</strong>, just like the pattern encourages.</p><h3>Final Thoughts</h3><p>The <strong>Builder Pattern</strong> may seem simple at first, but it solves a deeply practical problem: <strong>building complex objects without sacrificing readability or maintainability</strong>. Whether you’re configuring a plot in Matplotlib or assembling a configuration object in your own app, this pattern will help you write <strong>cleaner, more flexible, and scalable Python code</strong>.</p><p>If your constructors are starting to feel overloaded or if your objects are getting too many optional parameters, it’s time to consider the <strong>Builder Pattern</strong>.</p><p>In last, I would like to say!<br>Thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb33afff18ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Dynamic API Responses with Generics in FastAPI]]></title>
            <link>https://medium.com/@jkishan421/building-dynamic-api-responses-with-generics-in-fastapi-972fa1f52d54?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/972fa1f52d54</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 08:52:10 GMT</pubDate>
            <atom:updated>2025-01-30T08:52:10.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2eGDosSfyQF24HEy.png" /></figure><p>Python has supported <strong>type annotations</strong> since version 3.5, allowing developers to specify the expected data types in function signatures. While type annotations improve code clarity and correctness, they can be further enhanced using <strong>generic types</strong>. Generics enable us to define <strong>flexible and reusable type-safe structures</strong> that work with multiple data types without sacrificing precision.</p><p>You’ve likely already used generics in Python without realizing it — common built-in types such as list[int] or dict[str, int] are examples of generic data structures.</p><h4>The Problem Without Generics:</h4><p>When writing reusable code, you often encounter scenarios where you need to work with multiple data types. Without generics, you either:<br>✅ <strong>Sacrifice type safety</strong> by using Any or omitting type hints<br>✅ <strong>Duplicate code</strong> for different data types, making maintenance harder</p><h4><strong><em>Example:</em></strong></h4><p>let’s consider a function that reverses a list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*Vw-pkIq9Tx_KW0DMg07gww.png" /></figure><p><strong>🚨 Issues:<br></strong>1. No type hinting to specify what kind of list is expected<br>2. The function might accept non-list inputs, leading to unintended errors</p><h4>Solution: Using Generics</h4><p>Generics allow us to specify type parameters for functions and classes, ensuring type safety while maintaining flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ST_mKqsKcVl66R4ulZFvg.png" /></figure><h4>Benefits of Using Generics</h4><p>✔️ <strong>Type Safety:</strong> Ensures that functions and classes handle consistent data types.<br>✔️ <strong>Code Reusability:</strong> Avoids writing separate implementations for different types.<br>✔️ <strong>Readability:</strong> Makes code self-documenting and easier to understand.<br>✔️ <strong>Error Prevention:</strong> Tools like <strong>mypy</strong> can catch type mismatches before runtime.</p><h4>Example: Implementing a Generic Class</h4><p>A common use case for generics is data structures like a Stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxBAPZgO0qt9uxLWy5arPA.png" /></figure><p>Now that we understand <strong>how generics make Python code more reusable and type-safe</strong>, let’s see how they apply to <strong>Pydantic models in FastAPI</strong>. 🚀</p><h3>Generics + Pydantic</h3><p>Using generics with Pydantic in FastAPI allows you to create reusable and type-safe models that can work with different data types dynamically. This is useful when defining common response structures, paginated results, or wrappers around different data types.</p><h4>Why Use Generics in the Pydantic?</h4><p>Generics in Pydantic solve a key problem:<br><strong>Ensuring type safety while keeping code reusable.</strong></p><p>Even though Python itself doesn’t require strict typing, FastAPI and Pydantic use type hints to improve:</p><ol><li><strong>Data validation</strong> (ensuring correct types at runtime).</li><li><strong>Code reusability</strong> (avoiding duplicate models).</li><li><strong>Better autocompletion and documentation </strong>(helpful in large projects).</li><li><strong>Static analysis</strong> (with tools like mypy to catch errors before runtime).</li></ol><h4>Problem Without Generics:</h4><p>Suppose you’re building an API where every response follows a standard format:</p><p><strong><em>{ “status”: “success”, “data”: {…}, “message”: “Some message” }</em></strong></p><p>Option 1: Duplicating Pydantic Models for Each Response Type</p><p>If you don’t use generics, you’ll need a separate response model for each data type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*IYsRiAmJ1VQPzO2XYKirDQ.png" /></figure><p>This means if you add <strong>10+ different response types</strong>, you need <strong>10+ separate response models</strong> that only differ in the data field.<br>This is repetitive and hard to maintain.</p><h4>Solution: Use Generics to Remove Duplication</h4><p>With generics, we define one response model that can handle any data type dynamically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Wad2rbXY6qP6KYylAjDdZw.png" /></figure><p>Now, ApiResponse can be reused for <strong>any type</strong>, eliminating redundancy.</p><h4>How Does It Solve the Problem?</h4><p>Now, if you have multiple endpoints returning different data types, you <strong>reuse the same response model</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*2NqHW6dwrss8zsEYEF6CmQ.png" /></figure><h4>How It Helps</h4><p>✅ <strong>Removes redundancy</strong> → No need to create UserResponse, ItemResponse, etc.<br>✅ <strong>Ensures correct types</strong> → The response model always has a data field matching the expected type.<br>✅ <strong>Improves maintainability</strong> → If you need to change the response format, update <strong>one place</strong> instead of multiple.<br>✅ <strong>Static checking</strong> → Tools like mypy catch type mismatches before runtime.</p><h4>Using Generics for Paginated Responses in FastAPI with Pydantic</h4><p>A common use case for <strong>generics in Pydantic</strong> is creating a <strong>paginated response</strong> model that works with different types of data. This prevents repeating the same model for every endpoint.</p><h4>Problem: Without Generics</h4><p>If we need pagination for different data types (e.g., User, Item), we might define separate models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*LeWJmhoj_nsPesNlOOWWDA.png" /></figure><p><strong>Problem:</strong> Every new entity requires a new pagination model, making the code repetitive and hard to maintain.</p><h4>Solution: Using a Generic Pagination Model</h4><p>We define a <strong>single paginated response model</strong> using generics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*MMBSvsvKJF-uqsWqeSK08w.png" /></figure><p>✅ <strong>Now, this model works for any entity (User, Item, etc.).</strong></p><h4>Using the Generic Model in FastAPI</h4><p>Now, we can create paginated endpoints without defining separate response models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*68iRwbPaeu3znNFJHqPLWQ.png" /></figure><h4>Why Use Generics Here?</h4><p><strong>No Code Duplication</strong> → One PaginatedResponse model works for any data type.<br><strong>Type Safety </strong>→ items always has the correct type.<br><strong>Easier Maintenance</strong> → If you change pagination logic, update it in one place.<br><strong>Better Documentation</strong> → FastAPI’s OpenAPI schema automatically adapts.</p><h3>Conclusion</h3><p>Even though Python is dynamically typed, <strong>FastAPI and Pydantic leverage type hints</strong> to provide powerful <strong>data validation, better tooling, and improved developer experience</strong>.</p><p>By using <strong>Generics</strong>, we eliminate the need for repetitive model definitions, allowing us to create <strong>flexible, reusable models</strong> that dynamically adapt to different data types. This not only <strong>reduces code duplication</strong> but also <strong>improves maintainability, consistency, and type safety</strong> in FastAPI applications.</p><p>Embracing generics in Pydantic ensures that our API models remain <strong>scalable and future-proof</strong>, making our FastAPI applications <strong>more efficient and easier to manage</strong>. 🚀</p><p>In last, I would like to say!<br>Thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972fa1f52d54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Requests vs Aiohttp vs HTTPX: Choosing the right Python HTTP Libraries]]></title>
            <link>https://medium.com/@jkishan421/requests-vs-aiohttp-vs-httpx-choosing-the-right-python-http-libraries-8a06373e9744?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a06373e9744</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 10:53:00 GMT</pubDate>
            <atom:updated>2024-06-10T10:53:00.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io3NZexdi7XgXsyz.png" /></figure><p>In Python coding, being able to quickly and reliably send HTTP requests is super important for lots of things, like grabbing data from websites, connecting to APIs, or talking between different microservices of a program. <br>To achieve this in Python, we have three main tools for sending HTTP requests: <strong>requests</strong>, <strong>aiohttp</strong>, and <strong>httpx</strong>. <br>Each of these tools has its own strengths and is suited for different tasks. In this article, we’ll examine them closely to help you choose the best one for your needs. Whether you value simplicity, speed, or cutting-edge features, we’ll evaluate how each tool performs in these areas.</p><h3>Request:</h3><p>The <strong>requests</strong> library is the most popular Python library for making HTTP requests. It offers an easy-to-use interface that simplifies working with HTTP. However, it doesn’t support asynchronous operations or concurrent requests natively, meaning each request blocks the execution of your program until it completes.</p><h4>Example:</h4><p>In this example:</p><ol><li>We import the requests library and time module for measuring the duration.</li><li>We define two URLs to request data from.</li><li>We measure the start time before making any requests.</li><li>The first request is made to url1, and the program waits for this request to complete and prints the response.</li><li>The second request is made to url2 after the first request completes, and then it prints the response.</li><li>Finally, we measure the end time and print the total time taken for both requests.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f35KLnAZqqVa6P4JoXMHCA.png" /><figcaption>Total Time: 1.22 seconds</figcaption></figure><p>This demonstrates how the requests library handles HTTP requests sequentially, causing the second request to wait for the first one to finish.</p><h4>Problem 1:</h4><p>The great thing about requests is that it is extremely popular and easy to use. However, it is optimized for simplicity, not for performance. <br>By default, each time you send a request, a new session and connection are created, which can be time-consuming and inefficient. A better approach is to use a Session. <br>A Session manages a pool of connections for you, allowing you to reuse connections instead of creating a new one for each request. This makes your requests more efficient and improves performance.</p><h4>Example using session:</h4><p>In this example, a Session object is created and used to make both requests. This allows the session to reuse the connection, improving performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8mldBNYEcuZ3GjPPGhPrQ.png" /><figcaption>Total Time: 0.71 seconds</figcaption></figure><h4>Problem 2:</h4><p>Another limitation of requests is that it doesn&#39;t support concurrency; we are still sending these HTTP requests one after the other, waiting for each response before sending the next request. <br>There&#39;s no need to do this if the requests are independent of each other. We could send all the requests at the same time and get the results back as soon as each request is completed, without waiting for one request to finish before starting the next. <br>This is where a package like aiohttp comes in, which allows us to make HTTP requests concurrently, significantly improving performance.</p><h3>Aiohttp:</h3><p>Aiohttp library in Python is an asynchronous HTTP client and server framework that is built on top of the asynchronous I/O library asyncio in Python. Using this library, we can build web applications and RESTful APIs, and also we can handle synchronous HTTP requests in the application.</p><h4>Example:</h4><p>In this example:</p><ol><li>We import aiohttp and asyncio.</li><li>We define an asynchronous function fetch to send a GET request and return the JSON response.</li><li>We define an asynchronous main function to handle multiple requests concurrently.</li><li>We create a list of URLs and use aiohttp.ClientSession to manage the connections.</li><li>We create a list of tasks for fetching each URL and gather the results concurrently using asyncio.gather.</li><li>We measure and print the total time taken to complete the requests.</li></ol><pre>import aiohttp<br>import asyncio<br>import time<br><br>async def fetch(session, url):<br>    async with session.get(url) as response:<br>        return await response.json()<br><br>async def main():<br><br>    urls = [<br>        &#39;https://jsonplaceholder.typicode.com/posts/1&#39;,<br>        &#39;https://jsonplaceholder.typicode.com/posts/2&#39;<br>    ]<br><br>    async with aiohttp.ClientSession() as session:<br>        tasks = [fetch(session, url) for url in urls]<br>        responses = await asyncio.gather(*tasks)<br>        for response in responses:<br>            print(response)<br><br>start_time = time.time()<br># Run the asyncio event loop<br>asyncio.run(main())<br><br>end_time = time.time()<br><br>print(f&quot;Total time taken: {end_time - start_time} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5UlCmePoJIyMB-gG5jMNg.png" /><figcaption>Total Time: 0.54 seconds</figcaption></figure><p>This approach sends the requests concurrently, making the process much faster compared to sending them sequentially.</p><h4>Trade-off:</h4><p>The main difference between requests and aiohttp is that while requests is optimized for simplicity, aiohttp is optimized for performance. <br>With aiohttp, you need to create a session and use a context manager when calling the session, which can make your code more complex. <br>This approach is <strong>faster</strong>, but it means you&#39;ll have extra code even for simple tasks. <br>Many developers prefer simplicity over performance, which is why requests is more popular than aiohttp.</p><p><strong><em>There’s a trade-off: performance at the cost of simplicity, or simplicity at the cost of performance.</em></strong></p><h3>HTTPX:</h3><p>HTTPX is a fully featured HTTP client for Python 3, which provides synchronous and asynchronous request handling. It is built on top of the popular <a href="https://pypi.org/project/httpcore/">httpcore</a> library and designed to be highly performant.</p><p>It combines the simplicity and ease of use found in requests with the ability to perform asynchronous operations like aiohttp.</p><p>This makes httpx a versatile choice for developers who need a straightforward API but also want the option for high-performance, non-blocking requests.</p><h4>Sync Example:</h4><p>In this example:</p><ol><li>We import the httpx library and time module for measuring the duration.</li><li>We define two URLs to request data from.</li><li>We measure the start time before making any requests.</li><li>The first request is made to url1.</li><li>The second request is made to url2.</li><li>Creates an httpx.Client instance using a context manager (with statement). This ensures that resources are properly managed and the client is automatically closed after the block of code is executed.</li><li>Finally, we measure the end time and print the total time taken for both requests.</li></ol><pre>import httpx<br>import time<br><br>url1 = &#39;https://jsonplaceholder.typicode.com/posts/1&#39;<br>url2 = &#39;https://jsonplaceholder.typicode.com/posts/2&#39;<br><br>start_time = time.time()<br><br># Create a client -&gt; Like request.session<br>with httpx.Client() as client:<br>    response1 = client.get(url1)<br>    print(f&quot;First request completed: {response1.json()}&quot;)<br><br>    response2 = client.get(url2)<br>    print(f&quot;Second request completed: {response2.json()}&quot;)<br><br>end_time = time.time()<br><br>print(f&quot;Total time taken: {end_time - start_time} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWNnekqvUcWCau3Iaib2yw.png" /><figcaption>Total Time: 0.61 seconds</figcaption></figure><h4>Async Example:</h4><p>In this example:</p><ol><li>We import the httpx library, asyncio for handling asynchronous operations, and the time module for measuring the duration.</li><li>We define an asynchronous function fetch that sends a GET request to a URL using the provided client and returns the JSON response.</li><li>We define an asynchronous main function that creates a list of URLs to request data from.</li><li>Inside main, we create an httpx.AsyncClient instance using a context manager (async with statement). This ensures that resources are properly managed and the client is automatically closed after the block of code is executed.</li><li>We create a list of tasks for fetching each URL concurrently and use await asyncio.gather(*tasks) to run these tasks and collect their responses.</li><li>We print each response once the requests are completed.</li><li>We measure the start time before running the asynchronous event loop.</li><li>We run the main function using asyncio.run(main()).</li><li>Finally, we measure the end time and print the total time taken for both requests.</li></ol><pre>import httpx<br>import asyncio<br>import time<br><br>async def fetch(client, url):<br>    response = await client.get(url)<br>    return response.json()<br><br>async def main():<br>    urls = [<br>        &#39;https://jsonplaceholder.typicode.com/posts/1&#39;,<br>        &#39;https://jsonplaceholder.typicode.com/posts/2&#39;<br>    ]<br>    async with httpx.AsyncClient() as client:<br>        tasks = [fetch(client, url) for url in urls]<br>        responses = await asyncio.gather(*tasks)<br>        for response in responses:<br>            print(response)<br><br>start_time = time.time()<br>asyncio.run(main())<br>end_time = time.time()<br>print(f&quot;Total time taken: {end_time - start_time} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZO6B8fxqOlsvNSOylkI9oQ.png" /><figcaption>Total Time: 0.57 seconds</figcaption></figure><h3>Conclusion:</h3><p>In this article, we explored three prominent Python libraries for making HTTP requests: requests, aiohttp, and httpx. Each library has its unique strengths and is suited for different scenarios.</p><ul><li><strong>Requests</strong>: This library is known for its simplicity and ease of use, making it a favorite for developers who prioritize straightforward and readable code. However, it doesn’t support concurrency natively and can be less efficient for applications requiring multiple simultaneous requests.</li><li><strong>Aiohttp</strong>: Optimized for performance, aiohttp allows for asynchronous HTTP requests, making it suitable for applications that need to handle many requests concurrently. While it offers significant performance benefits, it requires more complexity in your code, such as managing sessions with context managers.</li><li><strong>HTTPX</strong>: Combining the best of both worlds, httpx provides both synchronous and asynchronous APIs. It offers the simplicity of requests along with the performance advantages of aiohttp. This versatility makes httpx a compelling choice for many modern Python applications.</li></ul><p>In summary, your choice of HTTP library in Python will depend on your specific needs and preferences. If you need simplicity and straightforward usage, requests is the way to go. For high-performance, non-blocking operations, aiohttp is ideal. If you want flexibility and the ability to choose between synchronous and asynchronous requests, httpx provides a balanced and modern solution. By understanding each library&#39;s strengths and use cases, you can make an informed decision that best aligns with your project requirements and coding style.</p><p>In last, I would like to say!<br>Thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a06373e9744" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieving 99% Accuracy in Brain Tumor Classification with YOLOv8]]></title>
            <link>https://medium.com/@jkishan421/achieving-99-accuracy-in-brain-tumor-classification-with-yolov8-64894cf01b54?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/64894cf01b54</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 12:56:30 GMT</pubDate>
            <atom:updated>2023-08-07T12:56:30.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*K1blSKnhuLzct3Y2pPRZYg.png" /></figure><p>Identifying brain tumors accurately and efficiently is a significant challenge in healthcare. In this article, we will explore a new approach to classify Brain Tumors with an accuracy of 99% using YOLOv8, a cutting-edge object detection model. By combining deep learning with medical imaging, we hope this approach will improve both the speed and accuracy of Brain Tumor identification.</p><p>To begin, we’ll obtain the Brain Tumor Classification dataset from <a href="https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri">Kaggle</a>. We’ll then utilize various data cleaning methods to prepare the data for input into our model. Next, we’ll download the YOLOv8 from Ultralytics and adjust it to our specific case. Finally, we’ll create a FastAPI application for simplified usage.</p><h4>1. Explore Dataset:</h4><p>Let’s take a closer look at the dataset we just downloaded from <a href="https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri">Kaggle</a>. The dataset has already been divided into train and test sets. There are four different tumor classes: Glioma, Meningioma, Pituitary, and NoTumor. Each class has about 1300 examples in the train set and around 300 examples in the test set.</p><h4>2. Data Preparation:</h4><p>During this process, we will utilize various techniques to clean our dataset images. These techniques include identifying and removing corrupt images, as well as eliminating images that are significantly small in size.</p><p><strong>2.1 Remove Corrupt Images:</strong></p><p>During this procedure, we must go through all the images in each class/category and verify if it can be opened using cv.imread. If it cannot be opened, it is imperative to delete it from our dataset as it may be a corrupted image or simply not an image file.</p><p><strong>2.2 Remove Images Below Threshold:</strong></p><p>Another data cleaning technique involves checking if an image falls below a certain size threshold and removing it. This is important because redundant data can negatively affect our model’s performance.</p><p>Here’s the code to remove all corrupt and below-threshold images at once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eaa9d4713b8d5230681006bc572d75d/href">https://medium.com/media/2eaa9d4713b8d5230681006bc572d75d/href</a></iframe><h4>3. Data Analysis:</h4><p>As part of our analysis, we will examine our dataset to determine the total number of records and the number of images for each class. We will also assess the distribution of classes and generate charts to enhance our understanding of the data.</p><p>This approach allows us to gain insights into the data to prevent overfitting and underfitting issues when feeding it into the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/263b232798ac032718d8e1965be5f17f/href">https://medium.com/media/263b232798ac032718d8e1965be5f17f/href</a></iframe><p>The code displayed will create two bar charts representing the number of images per class and the class distribution. The graphs indicate that our data is well-distributed, with a slightly larger number of images in the <strong>&quot;no-tumor&quot;</strong> class but still relatively balanced compared to the other classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*h41HQOs156QiZpo0qWU16Q.png" /></figure><h4>4. Data Visualization:</h4><p>Before feeding our data, it is important to visualize it with our own eyes for better understanding. The code provided below displays one image from each class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48bfcee5f608e61a140e3761f04c1be3/href">https://medium.com/media/48bfcee5f608e61a140e3761f04c1be3/href</a></iframe><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*qjLLIbrHStRhIEZED6vTzQ.png" /></figure><h4>5. Train the Model:</h4><p>In the Brain Tumor Classification project, we will utilize the YOLOv8 pre-trained model. Our first step will be importing this model into the project. Next, we will fine-tune the pre-trained model with our dataset. Finally, we will evaluate the model on our test data to determine the accuracy of each class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba5071f6e8533ac94741f9f33d9a4380/href">https://medium.com/media/ba5071f6e8533ac94741f9f33d9a4380/href</a></iframe><p>To obtain the normalized confusion matrix, navigate to the<strong> <em>runs/classify/val</em></strong> folder in the current directory.</p><p>Once there, you will be able to view it in the form of the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ID8UWcEx4he2R-RpICojw.png" /></figure><p>From the data presented, the model achieved 100% performance on three classes and 96% on one class (meningioma). Thus, the overall accuracy can be calculated as follows:<br>(100 x 3 + 96) / 4 = <strong>99%</strong>.</p><h4>6. Expose Endpoint for Testing Custom Images:</h4><p>For the project’s final step, we will establish an endpoint in FastAPI. This endpoint will accept an image as input and return the image label prediction. With this feature, we can easily test our model on any chosen image.<br>Upon fine-tuning the model, it generates another pre-trained model file (.pt) located in <strong><em>/run/classify/train/weights/best.pt</em></strong>. We will integrate this file into our FastAPI project.</p><p>Below is the code of FastAPI which runs on port <strong>8000</strong>, and has an endpoint of <strong>/images</strong>. This endpoint will take an image as an input and return the labels of that image predicted by our model <strong><em>(best.pt)</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca04442d8164f9316c07201ff3827b1b/href">https://medium.com/media/ca04442d8164f9316c07201ff3827b1b/href</a></iframe><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgTMdDLMdNMkbe0plujaPA.png" /></figure><h4>Conclusion:</h4><p>In summary, the data used for our article was acquired from the <a href="https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri">Kaggle</a> platform. Following this, we executed a cleaning process on the data and subsequently fed it into our model, which ultimately produced a comprehensive normalized confusion matrix. As a final step, we utilized FastAPI to establish an endpoint, which enables us to predict with great accuracy and efficiency and subsequently returns the class of any tumor image inputted into the system.</p><p>In last, I would like to say!<br>Thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64894cf01b54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Secrets of Design Patterns in Python: A Comprehensive Guide]]></title>
            <link>https://medium.com/@jkishan421/unlocking-the-secrets-of-design-patterns-in-python-a-comprehensive-guide-f2d1046bb28f?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2d1046bb28f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 12:26:53 GMT</pubDate>
            <atom:updated>2023-06-13T12:26:53.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*pF0dO1_jryo63gCp.png" /></figure><p>Software engineering has long been interested in design patterns. Design patterns help to solve common problems with an abstraction that works for certain scenarios. When they are implemented properly, the general design of the solution can benefit from them.</p><p>They provide a structured approach to solving problems and offer guidelines for organizing code and relationships between objects. Design patterns aim to improve software systems&#39; flexibility, maintainability, and scalability.</p><p>In Python, design patterns can be implemented using object-oriented programming features. Python’s dynamic nature and flexibility make it well-suited for implementing various design patterns.</p><p>Design patterns can be categorized into three main categories:</p><h4>Creational Patterns:</h4><p>Creational patterns focus on object creation mechanisms, providing flexibility in creating objects while minimizing dependencies.</p><p><strong><em>Types:</em></strong></p><ul><li><strong>Factory</strong>: Provides a way to create objects without specifying their exact class.</li><li><strong>Singleton</strong>: Ensures only one instance of a class is created.</li><li><strong>Shared State: </strong>Replicate the data across multiple instances.</li><li><strong>The Borg Pattern: </strong>Allows<strong> </strong>multiple instances of a class to share the same state while maintaining separate identities.</li><li><strong>Builder</strong>: Separates the construction of complex objects from their representation.</li></ul><h4>Structural Patterns:</h4><p>Structural patterns deal with object composition, simplifying the relationships between objects. They help in building flexible and efficient class structures.</p><p><strong><em>Types:</em></strong></p><ul><li><strong>Adapter</strong>: Allows objects with incompatible interfaces to work together.</li><li><strong>Composite</strong>: Treats individual objects and compositions of objects uniformly.</li><li><strong>Decorator</strong>: Dynamically adds functionality to objects.</li><li><strong>Facade: </strong>Simplify the interaction between objects.</li></ul><h4>Behavioral Patterns:</h4><p>Behavioral patterns focus on communication between objects and the assignment of responsibilities. They provide solutions for managing complex interactions and control flow.</p><p><strong><em>Types:</em></strong></p><ul><li><strong>Chain of Responsibility: </strong>Request is passed through a series of handlers.</li><li><strong>Template Method: </strong>Make objects more flexible and easier to change while preserving polymorphism.</li><li><strong>Command: </strong>Isolate the request.</li><li><strong>State: </strong>The State pattern is a design pattern that allows an object to alter its behavior when its internal state changes.</li><li><strong>Observer</strong>: Defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified.</li><li><strong>Strategy</strong>: Encapsulates interchangeable algorithms and allows them to be selected at runtime.</li><li><strong>Iterator</strong>: Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.</li></ul><p>By now, we have gained a fundamental understanding of design patterns, including their significance and applications. We have also explored the primary categories of design patterns. Now, let us delve into each type in detail.</p><h3>Creational Patterns:</h3><p>Creational patterns provide ways to create objects in a flexible and reusable manner while abstracting the details of the object instantiation process.</p><h4>Factory:</h4><p>The Factory pattern is a design pattern that helps in flexibly creating objects. It provides an interface for creating objects, but the actual class of the object is decided by subclasses. <br>This pattern allows the code to be more flexible and loosely coupled, as it separates the object creation logic from the client code. <br>Let’s understand it with a real-world scenario of vehicle creation in a manufacturing plant.</p><p><strong><em>Example:</em></strong></p><p>Consider a vehicle manufacturing plant that produces various types of vehicles, such as cars, motorcycles, and bicycles. Each type of vehicle has its specific manufacturing process and components.</p><p>Using the Factory pattern, we can create a VehicleFactory class that encapsulates the logic for creating different types of vehicles. The factory class can have a method like create_vehicle that takes a parameter specifying the type of vehicle to create.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c53f27ad165cd4098802e5d81173bfc6/href">https://medium.com/media/c53f27ad165cd4098802e5d81173bfc6/href</a></iframe><p><strong><em>In the above code, the output would be:<br></em></strong><em>Manufacturing a car.<br>Manufacturing a motorcycle.<br>Manufacturing a bicycle.</em></p><h4>Singleton:</h4><p>The Singleton pattern restricts the instantiation of a class to a single object and provides a global point of access to that object throughout the application.</p><p><strong><em>Example:</em></strong></p><p>Let’s consider that we have a singleton class of Database Connection Manger that returns us a database instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c182b29c9c1da74a52dc5c45ca49dd9/href">https://medium.com/media/2c182b29c9c1da74a52dc5c45ca49dd9/href</a></iframe><p>In this example, the __new__ method ensures that only one instance of the class is created. Both connection_manager1 and connection_manager2 refer to the same instance of the DatabaseConnectionManager class.</p><p>You can call the connect and disconnect methods on the shared instance, demonstrating the global access to the database connection manager.</p><h4><strong>The Borg Pattern:</strong></h4><p>The Borg pattern is a design pattern that allows multiple objects of a class to share the same state while still being treated as separate objects. It’s like having a group of friends who all have access to the same information or resources, but each person is still considered an individual.</p><p>It is similar to the Singleton pattern but with a key difference: in the Singleton pattern, there is only one instance of a class, whereas in the Borg pattern, multiple instances exist, but they share the same state.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b4afb0c70eba1ab20371b01f0673a6/href">https://medium.com/media/28b4afb0c70eba1ab20371b01f0673a6/href</a></iframe><p><strong><em>Output:<br></em></strong><em>Data updated by borg1<br>Data updated by borg1</em></p><p>In this example, the Borg class implements the Borg pattern. The _shared_state dictionary serves as the shared state among all instances of the class.</p><p>As seen in the example, when borg1 updates the shared_data, it reflects the change when accessing borg2.shared_data as well. This demonstrates that both instances share the same state and modifications are visible across all instances.</p><h4>Builder:</h4><p>The Builder pattern is a creational design pattern that separates the construction of complex objects from their representation.</p><p>It enables the creation of complex objects while hiding the internal implementation details.</p><p><strong><em>Example:</em></strong></p><p>In this example, the Computer class represents the complex object being built. The ComputerBuilder class separates the construction process from the Computer class. It provides methods to set the processor, memory, and storage of the computer. The build method returns the fully constructed computer object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e898490a4bd40d6175cebc7803f3c305/href">https://medium.com/media/e898490a4bd40d6175cebc7803f3c305/href</a></iframe><p><strong><em>Output:<br></em></strong><em>Computer: Processor=Intel Core i7, Memory=16GB, Storage=1TB SSD</em></p><h3>Structural Patterns:</h3><p>Structural patterns focus on the composition and organization of classes and objects to form larger structures, promoting code reusability, flexibility, and maintainability. They define relationships and interactions between components to enhance system design.</p><h4><strong>Adapter</strong>:</h4><p>It acts as a bridge between two incompatible interfaces by converting the interface of one class into another interface that clients expect.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3345d81de688b0d62e2f34635d26125/href">https://medium.com/media/f3345d81de688b0d62e2f34635d26125/href</a></iframe><p>In this example, the AudioPlayer class represents the existing music player that can play MP3 files. The AdvancedAudioPlayer class represents the new audio player that can play WAV and AAC files. The AudioPlayerAdapter class acts as an adapter, allowing the AudioPlayer to play WAV and AAC files by utilizing the AdvancedAudioPlayer.</p><h4>Composite:</h4><p>This pattern is a little bit more advanced than others, it describes a group of objects that are treated the same way as a single instance of the same type of objects. The purpose of the Composite Method is to <strong>Compose</strong> objects into Tree type structures to represent the whole-partial hierarchies.</p><p>A composite pattern is that the individual objects and composite objects share a common interface, enabling them to be used interchangeably. This promotes code reusability and simplifies the client code by treating the complex structure as a collection of individual objects.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b817658b4ff0035a641bd99a00237c7/href">https://medium.com/media/0b817658b4ff0035a641bd99a00237c7/href</a></iframe><p>In this example, we have a UniversityComponent abstract base class defining the common interface for universities and departments. The University class represents a university, which can have multiple departments. The Department class represents individual departments within the university.</p><h4><strong>Decorator<em>:</em></strong></h4><p>The Decorator pattern is a structural design pattern that allows you to dynamically add new behaviors or functionalities to an object by wrapping it in a decorator class. It provides an alternative to subclassing for extending the functionality of an object.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddedd8cb4abb9bcfe4e2eeaea7f5c9b/href">https://medium.com/media/4ddedd8cb4abb9bcfe4e2eeaea7f5c9b/href</a></iframe><p>In this example, we have a TextFormatter abstract base class defining the common interface for text formatters. The DefaultTextFormatter class represents a default text formatter that does not modify the text. The UppercaseTextFormatter and BoldTextFormatter classes are concrete decorators that wrap other text formatters and modify the text accordingly.</p><h4>Facade:</h4><p>The Facade pattern is a structural design pattern that provides a simplified interface to a complex subsystem of classes, making it easier to use and understand. It acts as a higher-level interface that hides the complexities of the underlying system.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878e06aa7be5734f1e29397dbbbce59f/href">https://medium.com/media/878e06aa7be5734f1e29397dbbbce59f/href</a></iframe><p>In this example, we have a simplified representation of an online shopping system. The InventorySystem, PaymentSystem, and ShippingSystem are subsystems that handle inventory, payment processing, and shipping, respectively.</p><p>The OrderFacade acts as a facade that provides a simplified interface to the complex subsystems. It encapsulates the interactions with the subsystems and provides a single method place_order() to place an order. The client only needs to interact with the facade without worrying about the internal complexities of the subsystems.</p><h3>Behavioral Patterns:</h3><p>Behavioral patterns in software engineering focus on the interaction and communication between objects, providing solutions for managing behaviors, object relationships, and complex workflows to design flexible and reusable systems.</p><h4><strong>Chain of Responsibility:</strong></h4><p>The Chain of Responsibility is a behavioral design pattern that allows an object to pass a request along a chain of potential handlers until the request is handled or reaches the end of the chain. Each handler in the chain has the ability to either handle the request or pass it to the next handler in the chain.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be173d5c0b02a796fcdcf74cd543e459/href">https://medium.com/media/be173d5c0b02a796fcdcf74cd543e459/href</a></iframe><p>In this example, we have a purchase request approval system with different levels of approvers (Manager, Director, CEO). Each approver has a limit on the purchase amount they can approve.</p><h4>Template Method:</h4><p>The Template Method pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to provide their implementations for certain steps of the algorithm while keeping the overall structure unchanged.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddb89596e78083c7e2eb40b104cf1da2/href">https://medium.com/media/ddb89596e78083c7e2eb40b104cf1da2/href</a></iframe><p>In this example, we have a Beverage abstract class that defines the template method prepare() for preparing a beverage. The template method calls other methods such as boil_water(), brew(), pour_in_cup(), and add_condiments(). Some of these methods are implemented in the base class, while others are left abstract to be implemented by concrete subclasses.</p><h4>Command:</h4><p>The Command pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing a parameterization of clients with different requests, queueing or logging of requests, and support for undoable operations.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/791ae06d3f9508255c9a3594aec0d1ca/href">https://medium.com/media/791ae06d3f9508255c9a3594aec0d1ca/href</a></iframe><p>In this example, we have a remote control that can be used to control light. The Command pattern is implemented using the Command interface, which defines the execute() method. The concrete command classes (LightOnCommand and LightOffCommand) implement the Command interface and encapsulate the specific operations to turn the light on and off.</p><p>The Light class acts as the receiver, which performs the actual actions of turning the light on and off. The RemoteControl class acts as the invoker, which holds a reference to the current command and executes it when the press_button() method is called.</p><h4>State:</h4><p>The State pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. It encapsulates each state as a separate class and delegates the behavior to the current state object.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1217861a4c65f82319c3538c682145ef/href">https://medium.com/media/1217861a4c65f82319c3538c682145ef/href</a></iframe><p>In this example, we have a TrafficLight class that acts as the context. It has a current state represented by the state attribute. The context delegates the handling of requests to the current state object.</p><p>The TrafficLightState interface defines the common methods that each concrete state class must implement. In this example, we have three concrete state classes: RedState, GreenState, and YellowState. Each state class represents a different state of the traffic light and defines its behavior when a request is received.</p><p>When the request() method is called on the TrafficLight object, it delegates the request handling to the current state object. The state object performs its specific behavior and can also change the state of the context if needed.</p><h4>Observer:</h4><p>The Observer pattern is a behavioral design pattern that establishes a one-to-many dependency between objects, where multiple observers are notified and updated automatically when the state of a subject object changes.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1544996b546055ce95ea346a0ee3c3ed/href">https://medium.com/media/1544996b546055ce95ea346a0ee3c3ed/href</a></iframe><p>In this example, we have a StockMarket class that acts as the subject or publisher. It maintains the current stock price and a list of observers. Observers can subscribe to the stock market to receive updates when the stock price changes.</p><h4>Strategy:</h4><p>The Strategy pattern is a behavioral design pattern that allows you to define a family of interchangeable algorithms and encapsulate each one as an object. This pattern enables the algorithms to be selected at runtime, promoting flexibility and extensibility.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad3e7e276fe41ccd3b1a2c739a9b3a18/href">https://medium.com/media/ad3e7e276fe41ccd3b1a2c739a9b3a18/href</a></iframe><p>In this example, we have a SortingStrategy interface that defines the common method sort() for different sorting algorithms. The concrete strategy classes, BubbleSortStrategy and QuickSortStrategy, implement the sort() method with their respective sorting algorithms.</p><p>The Sorter class acts as the context that uses the sorting strategies. It has a strategy attribute that holds the current strategy object. The sort_data() method is used to perform sorting by delegating the sorting operation to the strategy object.</p><h4><strong><em>Iterator:</em></strong></h4><p>The Iterator pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.</p><p><strong><em>Example:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b33618997433cd717fc113c03168d87d/href">https://medium.com/media/b33618997433cd717fc113c03168d87d/href</a></iframe><p>In this example, we have an Iterator interface that defines the methods for iterating over elements, such as has_next() and next(). The ListIterator class implements the iterator interface and provides the implementation for iterating over a list.</p><p>The ListCollection class represents the aggregate object, which holds a collection of items. It has a create_iterator() method that creates a ListIterator object for iterating over the collection.</p><p>The client code can use the iterator to access the elements of the collection without knowing its internal structure. It simply calls has_next() to check if there are more elements and next() to retrieve the next element.</p><h3>Conclusion:</h3><p>In conclusion, design patterns in Python provide reusable solutions to common software design problems. They help improve the structure, flexibility, and maintainability of your code by promoting modular and loosely coupled designs.</p><p>There are three main types of design patterns:</p><ol><li><strong>Creational Patterns</strong>: These patterns focus on object creation mechanisms, providing ways to create objects in a flexible and controlled manner.</li><li><strong>Structural Patterns</strong>: These patterns deal with the composition of classes and objects, providing ways to form larger structures while keeping them flexible and efficient.</li><li><strong>Behavioral Patterns</strong>: These patterns address communication between objects and the assignment of responsibilities, enabling objects to work together cohesively.</li></ol><p>By understanding and applying design patterns, you can improve the design of your Python applications, make them more maintainable, and enhance their extensibility. Design patterns provide proven solutions to common design problems, allowing you to leverage best practices and industry-standard approaches in your code. However, it’s important to apply design patterns judiciously and adapt them to the specific needs of your application, as blindly applying patterns without careful consideration can lead to unnecessary complexity.</p><p>In last, I would like to say!<br>Thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>Keep learning and exploring different design patterns, as they can greatly enhance your skills as a software developer. With practice and experience, you will become proficient in applying the right patterns at the right time, leading to well-designed and maintainable code.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><h4>Happy coding!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2d1046bb28f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the SOLID principles: How to design robust, maintainable, and extensible code in Python]]></title>
            <link>https://medium.com/@jkishan421/the-solid-principles-in-python-ea485c409c1a?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea485c409c1a</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 16:54:44 GMT</pubDate>
            <atom:updated>2023-01-22T21:12:04.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dy_kNvdUETy-WlFI.png" /></figure><p>In this article, we will learn about the <strong>SOLID </strong>principle and how to implement them in a pythonic way. These principles entail a set of effective practices for ensuring better-quality software, In case some of you aren’t aware of what SOLID stands for, here it is:</p><p><strong>S</strong>: Single responsible principle<br><strong>O</strong>: Open/closed principle<br><strong>L</strong>: Liskov’s substitution principle<br><strong>I</strong>: Interface segregation principle<br><strong>D</strong>: Dependency inversion principle</p><h3>The Single Responsibility Principle (SRP):</h3><p>The <strong>single responsibility principle (SRP)</strong> states that a software component (in general, a class) must have only one responsibility. The fact that the class has sole responsibility means that it is in charge of doing just one concrete thing, and as a consequence of that, we can conclude that it must have only one reason to change. This makes the code more maintainable and easier to understand, as changes to the codebase are more localized and less likely to affect other parts of the system.</p><h3>Example:</h3><h4>A class with too many responsibilities</h4><p>Let’s assume we have a class that reads data from a CSV file, processes it, and writes the processed data into another file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*NobSOb6YwVhYifuNtoHAKQ.png" /></figure><p>The problem with this class is that it defines a set of methods that correspond to orthogonal actions, each one can be done independently of the rest.</p><p>This design flaw makes the class rigid, inflexible, and error-prone because it is complicated to maintain. In this example, each method represents a responsibility of the class. Each responsibility implies a reason for updating the class. In this case, each method represents one of the reasons why the class will need to be modified in this case.</p><p><strong>SRP conformity</strong> is not achieved with this design.</p><h4>Distributing responsibilities</h4><p>To make the solution more maintainable, we separate every method into a different class. This way, each class will have a single responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*4HE5H0hIIAVp8jtjaUJThQ.png" /></figure><p>In this example, each class has a single responsibility:</p><ul><li>The CsvReader class is responsible for <strong>reading </strong>data from a CSV file.</li><li>The DataProcessor class is responsible for <strong>processing </strong>the data.</li><li>The DataExporter class is responsible for <strong>exporting </strong>the processed data to a file.</li></ul><p>Each class can be easily reused and tested in isolation, and changes to one class won’t affect the others. For example, if we want to change the way the data is processed, we can modify the DataProcessor class without affecting the other classes.</p><p>It’s also worth noting that the CsvReader, DataProcessor and DataExporter classes are loosely coupled and they depend on interfaces (methods) not on implementations. This allows us to change the implementation of a class without affecting the other classes.</p><p>In addition, applying the SRP can also be done by keeping functions small and focused, and ensuring that each function only has one responsibility. This makes the code more readable and reduces the chances of introducing bugs or breaking changes.</p><h3>The Open/Closed Principle (OCP):</h3><p>The <strong>open/closed Principle (OCP)</strong> states that a class should be open for extension, but closed for modification. This means that a class should be designed so that it can be extended to add new functionality, without modifying its existing code.</p><p>If for some reason, when something new has to be added we find ourselves modifying the code, then that logic is probably poorly designed. Ideally, when requirements change, we want to have to extend the module with the new behavior, but without having to alter the current logic significantly.</p><p>In Python, the Open/Closed Principle can be applied by using inheritance, polymorphism, and composition. For example, instead of modifying the code of a class to add new functionality, you can create a new subclass that inherits from the original class and overrides or extends its methods.</p><h3>Example:</h3><h4>Non-compliance with OCP</h4><p>Consider a code defines several classes: Shape, Rectangle, Circle, Square and AreaCalculator. The Shape class is an abstract class that has a type attribute and an abstract area method that does nothing. The Rectangle and Circle classes both inherit from Shape and have their own __init__ methods that set the shape&#39;s type and additional attributes (width and height for rectangles, radius for circles). Both classes also have their own area methods that calculate and return the area of the shape. The Square class inherits from the Rectangle class and overrides the __init__ method to set the width and height to the same value, and type to &quot;square&quot;.</p><p>In last we have an AreaCalculator class with __init__ method that takes a list of shapes as an argument, and a total_area method that iterates through the list of shapes, checks the type of each shape, and adds the area of each shape to a running total, returning the total area of all shapes in the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d61bb5d3cf7f3121ec85bd5400c131/href">https://medium.com/media/13d61bb5d3cf7f3121ec85bd5400c131/href</a></iframe><p>This code violates the open-closed principle because the AreaCalculator class must be modified every time a new type of shape is added. For example, if a new shape &quot;Triangle&quot; is added, the total_area method in the AreaCalculator class must be modified to include logic for calculating the area of a triangle. This makes the class not open for extension and closed for modification.</p><h4>Refactoring the shape class for extensibility</h4><p>In this refactored code, the AreaCalculator class does not need to know the specific types of shapes it is working with. Instead, it simply calls the area() method on each shape, which is implemented by each shape class. This means that the AreaCalculator class is open for extension, since new shape classes can be added without modifying the AreaCalculator class, and it is closed for modification since the total_area() method does not need to be changed when new shapes are added.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73942a52ebe80e31f3413fc5f8915a31/href">https://medium.com/media/73942a52ebe80e31f3413fc5f8915a31/href</a></iframe><p>This principle tackles an important problem in software engineering: maintainability. The perils of not following the OCP are ripple effects and problems in software where a single change triggers changes all over the code base, or risks breaking other parts of the code.</p><h3>Liskov’s Substitution Principle (LSP):</h3><p>The <strong>Liskov Substitution Principle (LSP)</strong> is a principle in object-oriented programming that states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program.</p><p>The main idea behind LSP is that, for any class, a client should be able to use any of its subtypes indistinguishable, without even noticing, and therefore without compromising the expected behavior at runtime. That means that clients are completely isolated and unaware of changes.</p><p>In other words, if a class S is a subclass of class T, then objects of class T should be able to be replaced with objects of class S without causing any issues.</p><h3>Example:</h3><h4>Failure to comply with LSP</h4><p>In this example let’s say we have a class definition for a BankAccount and a SavingAccount in Python. The BankAccount class has an initial balance, which can be modified through the deposit and withdraw methods. The withdraw method raises a ValueError if the amount to be withdrawn is greater than the current balance.</p><p>The SavingAccount class inherits from the BankAccount class and has an additional interest rate attribute. It overrides the withdraw method and takes into account the interest rate when checking for sufficient balance. It also has an additional add_interest method that adds interest to the balance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78cf522614deb48bd7e1406209ae2481/href">https://medium.com/media/78cf522614deb48bd7e1406209ae2481/href</a></iframe><p>In this example, the SavingAccount class inherits from the BankAccount class but overrides the withdraw method and modifies its behavior. The withdraw method of SavingAccount takes into account the interest rate and subtracts it from the balance when checking if there is enough balance to withdraw. This means that the SavingAccount class is not substitutable for the BankAccount class without causing issues, breaking the Liskov Substitution Principle.</p><p>For example, if we have a list of bank accounts and add both BankAccount and SavingAccount objects to it, and we iterate over the list and call the withdraw method on each object with the same amount, the behavior will be different for each object because SavingAccount class&#39;s withdraw method is different than the BankAccount class&#39;s withdraw method.</p><p>It is important to remember that LSP states that any implementation of a superclass should be substitutable for its subclasses without altering the desirable properties of that program.</p><h4>Conforms to LSP</h4><p>As mentioned in my above example, this implementation violates the <strong>LSP</strong> because the SavingAccount class&#39;s withdraw method is different than the BankAccount class&#39;s withdraw method. The SavingAccount class should be designed in such a way that it is substitutable for the BankAccount class without causing issues, for example by creating a new class <strong>InterestAccount, </strong>and let <strong>SavingAccount </strong>inherit from it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d727414134f04bdf5f53c5a2b637d45/href">https://medium.com/media/2d727414134f04bdf5f53c5a2b637d45/href</a></iframe><p>The SavingAccount class can be used as a substitute of the BankAccount class without any issues because it implements the same behavior as the BankAccount class, as well as additional behavior specific to saving accounts. This means that the SavingAccount class follows the Liskov Substitution Principle.</p><p>For example, we can create a list of bank accounts and add both BankAccount and SavingAccount objects to it, and we can iterate over the list and call the deposit and withdraw methods on each object without any issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*kF9_SoGC6ohrh59BwwhfXA.png" /></figure><p>The LSP is fundamental to good object-oriented software design because it emphasizes one of its core traits — <strong>Polymorphism</strong>. It is about creating correct hierarchies so that classes derived from a base one are polymorphic along the parent one, concerning the methods on their interface.</p><h3>Interface Segregation</h3><p>In object-oriented programming, the Interface Segregation Principle (ISP) states that a client should not be forced to implement interfaces it does not use. In other words, it is a principle that states that a class should not be forced to implement methods that it does not need or use.</p><p>In object-oriented terms, an interface is represented by a set of methods and properties and object expose. That is to say that all the messages that another client can request. The interface separates the definition of the exposed behavior for a class from its implementation.</p><p>In Python, interfaces are not explicitly defined like in some other programming languages, but the concept of interfaces can be implemented using abstract base classes (<strong>ABCs</strong>). An <strong>ABC </strong>is a class that defines a set of methods that derived classes are expected to implement.</p><h3>Example</h3><h4>Inability to follow Interface Segregation</h4><p>Let’s say we have a system that manages different types of vehicles, such as cars, trucks, and buses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee64efbe43710de9551376912d7094ed/href">https://medium.com/media/ee64efbe43710de9551376912d7094ed/href</a></iframe><p>In this example, the Vehicle class defines four methods: start_engine, stop_engine, honk, and load_cargo. These methods are implemented in the derived classes Car, Truck and Bus. The Car and Bus classes raise NotImplementedError when the load_cargo method is called, as they are not able to load cargo. This is a <strong>violation </strong>of the Interface Segregation Principle, because both Car and Bus classes are forced to implement the load_cargo method, even though they cannot use it.</p><h4>Keep to the Interface Segregation</h4><p>To correct the above example, we can create a new interface Loadable with the method load_cargo, and let only the Truck class implements it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e7aef9f415d110e07cabbda44152a2/href">https://medium.com/media/85e7aef9f415d110e07cabbda44152a2/href</a></iframe><p>In this refactored code, a new interface Loadable is created with the method load_cargo , and only the Truckclass implements it. This way, the Carand Busclasses do not need to implement the load_cargomethod, as they cannot use it. This adheres to the Interface Segregation Principle, where a class should not be forced to implement interfaces it does not use.</p><p>This design also increases the flexibility of the system, as it allows us to add new functionality (loading cargo) to the truck class without affecting the other classes. Also, it makes the code more readable and maintainable.</p><p>It is worth noting that, in python, the Interface Segregation Principle is not a hard rule but more of a guideline, as python does not have explicit interface declarations. But the above solution is a way to achieve ISP in python.</p><h3>Dependency Inversion</h3><p>The Dependency Inversion Principle (<strong>DIP</strong>) is a principle that states that the high-level modules of a software system should not depend on the low-level modules, but rather both should depend on abstractions.</p><p>Imagine that two objects in our design need to collaborate, <em>A </em>and <em>B</em>. Works with an instance of <em>B</em>, but as it turns out, our module doesn’t control <em>B </em>directly (it might be an external library, or a module maintained by another team, and so on). If our code heavily depends on <em>B</em>, when this changes, the code will break. To prevent this, we have to invert the dependency: make <em>B </em>have to adapt to <em>A</em>. This is done by presenting an interface and forcing our code not to depend on the concrete implementation of <em>B</em>, but rather on the interface we have defined. It is then <em>B</em>’s responsibility to comply with that interface.</p><h4>A case of rigid dependencies</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7604bdc7d950e1b6bb67b9b857961dff/href">https://medium.com/media/7604bdc7d950e1b6bb67b9b857961dff/href</a></iframe><p>In this example, the Application class depends directly on the Database class. This makes it difficult to change the implementation of the Database class without affecting the Application class.</p><h4>Inverting the dependencies</h4><p>To apply the Dependency Inversion Principle, we can create an abstraction for the database and let the Application class depends on this abstraction instead of the concrete implementation of the Database class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/079495a201d8caab22d86e55adefa467/href">https://medium.com/media/079495a201d8caab22d86e55adefa467/href</a></iframe><p>In this example, the Application class depends on the abstraction Database, and MySQLDatabase and MongoDBDatabase are the concrete implementations of the Database. The Application class does not know the concrete class of the database it is working with, it only knows that it is working with an instance of Database. It means that the Application is not tightly coupled to the concrete class, if in the future we decide to change the underlying database, we can do this by just replacing the MySQLDatabase or MongoDBDatabase with a new implementation without affecting the Application class.</p><p>This design makes the code more flexible and easier to maintain, as the high-level components depend on abstractions rather than on concrete implementations. The Dependency Inversion Principle helps to decouple the different parts of a software system, making it more maintainable and easier to change.</p><h3>Summary</h3><p>In closing, the SOLID principles are a set of guidelines that can help developers to design more robust, maintainable, and extensible code. By adhering to the Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles, developers can create code that is easier to understand, modify, and extend.</p><p>It’s important to remember that these principles are not strict rules and that the best solution for a given problem depends on the specific context and requirements. However, applying these principles can help developers to think about how to design their code in a way that makes it more maintainable and less error-prone.</p><p>It’s also important to keep in mind that, these principles are not limited to Python and can be applied to many other programming languages as well. The SOLID principles are a set of guidelines that help developers to create better code, and following them will lead to a more maintainable and scalable codebase in the long run.</p><p>In last, I would like to thank you for your valuable time. Please send me notes on this article if you have any questions regarding the topic.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea485c409c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dataclasses — An Awesome approach for OOP in Python]]></title>
            <link>https://medium.com/@jkishan421/dataclasses-an-awesome-approach-for-oop-in-python-50bc8b973b09?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/50bc8b973b09</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-dataclass]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Wed, 07 Sep 2022 13:53:23 GMT</pubDate>
            <atom:updated>2022-09-07T13:53:23.894Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Dataclasses</strong> — An Awesome approach for OOP in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b70ATyWv27OZiSXf.jpg" /></figure><p>There are two programming approaches: <strong><em>functional</em></strong> and <strong><em>object-oriented</em></strong>. <strong>Object-Oriented Programming (OOP)</strong> has been around for longer and is more popular, but <strong>Functional Programming (FP)</strong> is starting to catch up. The main difference between OOP and FP is that OOP emphasizes <strong><em>objects</em></strong> and <strong><em>methods</em></strong>, whereas FP emphasizes <strong><em>variables</em></strong> and <strong><em>functions</em></strong>. You can find more about FP and OOP <a href="https://webo.digital/blog/object-oriented-vs-functional-programming/">here</a>.</p><p>The building block that leads to Object-Oriented programming is a c<strong>lass</strong>. A class is an instance of a user-defined data type that contains its data members and member functions. A class is like a blueprint for an object.<br><strong><em>Example:</em></strong> Person, Vehicle, Point, etc.</p><h3>Parts of Classes:</h3><p>Classes are combinations of two things, <strong>behavior</strong> in terms of methods, and <strong>data</strong> in terms of attributes.</p><h4>1. Behavior Classes:</h4><p>A class that is responsible for some actions/behavior.<br><strong><em>For example,</em></strong> A class is responsible for drawing all kinds of shapes, or a class that provides password hashing functionality, etc.</p><h4>2. Data Classes:</h4><p>The classes that contain data, like a vehicle class, are responsible for holding vehicle data in the vehicle management system, or a student class that holds student information in a university.<br>Computer science makes extensive use of data classes, including comparing objects, displaying objects, and many other operations.<br>Normal classes don’t provide these functionalities by default, that’s why Python 3.7 introduces the <strong>dataclasses</strong> modules.</p><h3>Data classes and Simple classes:</h3><h4>1. Constructor</h4><p>In normal classes, we have to write the <strong><em>__init__()</em></strong> method, and overload it manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1c04831084418a0be8c907e36479dfa/href">https://medium.com/media/a1c04831084418a0be8c907e36479dfa/href</a></iframe><p>In data classes, we have a built-in <strong><em>__init__()</em></strong> method to quickly fill an object with data. We just need to define our attributes with datatypes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc8c7ac45883e6220d6a05bb278e7caa/href">https://medium.com/media/bc8c7ac45883e6220d6a05bb278e7caa/href</a></iframe><h4>2. Display Object</h4><p>The default behavior of normal classes is to <strong>display the object memory address</strong> when we print a class object (without overloading <strong><em>__repr__()</em></strong> and <strong><em>__str__()</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*Jq4AdEI1vFFcPfhOR0Malw.png" /><figcaption>Normal Classes</figcaption></figure><p>In contrast, data classes overload the <strong><em>__repr__()</em></strong> method for us to display the information of the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*VW4GyssuAckTDfq6tKsnCQ.png" /><figcaption>Data Classes</figcaption></figure><h4>3. Compare Objects</h4><p>Normal classes cannot compare two objects unless we overload the dendur methods like <strong><em>__eq__</em></strong>, <strong><em>__ge__</em></strong>, <strong><em>__le__</em></strong>,etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*f2bp7xhi6eIbWdZ3w_TgLw.png" /><figcaption>Comparison in normal classes</figcaption></figure><p>But in data classes, we can compare objects by using the <em>sort_index</em> attribute.To compare our objects on the basis of their <strong>age</strong> in the above example, Firstly we define <strong><em>order=True</em></strong> in the decorator of dataclass to make this class comparable. Secondly, we create a new attribute <strong><em>sort_index</em></strong>, which neither can be initialized nor displayed (because we use it only for sorting). Finally, in the <strong><em>__post_init__()</em></strong> <a href="https://www.geeksforgeeks.org/dunder-magic-methods-python/"><strong><em>dendur</em></strong></a> method we set the <strong><em>sort_index</em></strong> to <strong><em>age</em></strong> in order to make the objects comparable by <strong>age</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*msXdnye2A4Iw1WGhG_lT-Q.png" /><figcaption>Comparing on the basis of age in dataclasses</figcaption></figure><h4>4. Freeze Class</h4><p>We can freeze a dataclass just by adding <strong><em>frozen=True</em></strong> in the decorator of dataclass. After freezing a class we are not allowed to mutate its attribute values. Making things immutable, simplify the code. We don’t need to worry about whether something has been changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*8BYngFTFGZpgH_BSCBg9bA.png" /><figcaption>Assignment not allowed in frozen dataclass</figcaption></figure><h4>5. Default Attributes</h4><p>We can provide default values in dataclasses using <strong><em>default_factory. </em></strong>Let&#39;s suppose in the above <strong>Person</strong> class, we have an attribute to store email data in a list.</p><p><a href="https://gist.github.com/jkishan421/094ec4dbb063f8722475ddc790b906ab">https://gist.github.com/jkishan421/094ec4dbb063f8722475ddc790b906ab</a></p><h4>6. Control Attributes</h4><p>In dataclasses, we can also control which attributes are allowed to initialize and displayed at runtime. Let&#39;s suppose we have an <strong><em>id</em></strong> attribute in the Person class, we can restrict it from initializing and displaying by setting <strong><em>init=False</em></strong> and <strong><em>repr=False</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6Qlp7ne9Q_7XPEeYQfQrg.png" /><figcaption>Id not displayed</figcaption></figure><h4>7. Keyword Only</h4><p>The <strong><em>kw_only functionality </em></strong>restricts you to using the keyword arguments only when creating the objects of the class.<strong><em> <br>Note: </em></strong>This feature is only available in <strong><em>Python 3.10 </em></strong>and onwards.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8c025c413d0e17fda7ad7c99544821/href">https://medium.com/media/3d8c025c413d0e17fda7ad7c99544821/href</a></iframe><h3>Conclusion</h3><p>In this article we learned about <strong>dataclasses</strong> in Python, which are easier to understand and more useful than ordinary classes. Firstly, <strong>creating</strong> objects, <strong>displaying</strong> objects, and comparing <strong>objects</strong> are far easier than using normal classes. Secondly, we learn about the <strong>frozen</strong> <strong>classes</strong> in dataclass, how we can pass <strong>default values </strong>to attributes, and how to restrict them from being <strong>displayed</strong> or <strong>initialized</strong>. Lastly, in Python 3.10 we have seen how dataclasses use kw_only.</p><p>In closing, I would like to thank you for your valuable time. Please send me notes on this article if you have any questions regarding dataclasses.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><h3>References:</h3><p><a href="https://docs.python.org/3/library/dataclasses.html">https://docs.python.org/3/library/dataclasses.html</a></p><p><a href="https://www.youtube.com/watch?v=vRVVyl9uaZc&amp;ab_channel=ArjanCodes">https://www.youtube.com/watch?v=vRVVyl9uaZc&amp;ab_channel=ArjanCodes</a></p><p><a href="https://www.youtube.com/watch?v=CvQ7e6yUtnw&amp;ab_channel=ArjanCodes">https://www.youtube.com/watch?v=CvQ7e6yUtnw&amp;ab_channel=ArjanCodes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50bc8b973b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Hints in Python — Must to Use.]]></title>
            <link>https://medium.com/@jkishan421/type-hints-in-python-must-to-use-665afa2a4560?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/665afa2a4560</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[type-hints]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Tue, 23 Aug 2022 11:25:06 GMT</pubDate>
            <atom:updated>2022-08-23T13:22:06.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type Hints in Python — Must to Use.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rL9LEZcnPvLzyJ4LTzjZDw.jpeg" /></figure><p>In terms of effective programming, there is a famous quote:</p><p><em>“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”</em></p><p>It is essential to be familiar with type hints if one wishes to write clean code. This feature must be present in clean code.</p><h4>What are Type hints?</h4><p>Type hints are most closely associated with Python. Most languages are statically typed languages, while Python is dynamically typed.</p><p>In <strong>Static Typed</strong> languages, you need to specify the data type of the function’s arguments, return type of the function and data type of variables, etc.<br><strong><em>Examples</em></strong> of static type languages are C, C++, JAVA, GoLang, Scala, etc.</p><p>In <strong>Dynamic Typed</strong> languages, you don’t need to specify the data type of a variable, function’s return type, argument of functions, etc.<br><strong><em>Examples</em></strong> of static type languages are Python, PHP, JavaScript, etc.</p><p>You can find more about static and dynamic languages <a href="https://stackoverflow.com/a/1517670"><strong><em>here</em></strong></a>.</p><p><strong>Python is a dynamically typed language</strong>, so we don’t need to provide data type, but instead, we can provide type hints; which are very helpful for a couple of the following reasons.</p><h4>1. Detect Errors before Compilation</h4><p>Here we have a function named <strong>outer_func()</strong>, which takes a string of numbers, checks for even numbers, and returns the count of even numbers.<br>Inside of the function, we have one nested function named <strong>inner_func()</strong> which just converts a string into a list of integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48552229dcbc045fa0597759cc55cd49/href">https://medium.com/media/48552229dcbc045fa0597759cc55cd49/href</a></iframe><p>This code shown in the above image is without type hints. If we try to pass an integer in the function instead of a string, it will allow us to do it but will throw an error after compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*hh4efRceaQJy4awn4WGuoQ.png" /><figcaption>Error after passing an integer to outer_func()</figcaption></figure><p>But if we used the type hints in the above code, it will show as an error on passing an integer even before compiling it. Let’s have a look at the following code with type hints.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca1f1129abc58a06b852c0fe21eaa3a/href">https://medium.com/media/fca1f1129abc58a06b852c0fe21eaa3a/href</a></iframe><p>Here we provide the data types for every variable, parameters of functions, and return type of functions. In this case, if we pass the integer, while the function was expecting a string, we got an error before compiling the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Ik_gY3_PFWB_8X_LacirDQ.png" /><figcaption>Error before compilation</figcaption></figure><h4>2. Helps to write shorter documentation</h4><p>The documentation of code is critical to software development, but almost no programmer enjoys writing it. Documentation tells about the function’s job, specifies what arguments look like, and what it returns. Type hints have done this job for us, so need to write the documentation 😊.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a9fe2961d1d18d54750edd9386db729/href">https://medium.com/media/2a9fe2961d1d18d54750edd9386db729/href</a></iframe><h4><strong>3. Be explicit about your data structure</strong></h4><p>By using type hint in code, you have a clear idea of what the data looks like. It makes it easier to write a piece of software with known types before designing. It also discouraged your behavior which may result in messy code. This includes changing data structure on the fly, dynamically adding attributes to an object, creating data structures that are too large, etc.</p><p><strong><em>Example: </em></strong>Let’s see the following code; it defines a function named <strong>is_eligible()</strong>, which checks whether an employee is eligible for a bonus. The bonus is eligible for an employee who has a family or works more than 40 hours per week.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f2a799e0143c2d2433fbb4164087a71/href">https://medium.com/media/4f2a799e0143c2d2433fbb4164087a71/href</a></iframe><p>Here we can see a problem with this code, it does not always return a boolean value. In the case of not having a family, and working fewer than 40 hours per week, we get <strong>None</strong> in return. However, we were expecting always a boolean value from this function. So these kinds of problems are difficult to catch while we have complex functions. <strong>Type hints help us</strong> to avoid these types of errors. When we provide the return type of this function, we will get to know about possible errors before compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*sdgWLk9__nDyswP0vW1zww.png" /><figcaption>Getting possible errors indication before compilation</figcaption></figure><p>When we add return type bool to our function, we just got a warning that this function does not always return a boolean value. So this is how we can avoid possible errors before we commit them with the help of type hints.</p><h4>4. Simplify your code</h4><p>In the code with no type hints, we may have multiple if statements in the function body. These statements are to check that the parameters you get are actually what you are expecting them to be. Type helps to reduce this kind of code. If you need to rely on data from a file, where you don’t have control over the data structure, type hints provide you with some control. You can also use the <a href="https://pydantic-docs.helpmanual.io/"><strong><em>Pydantic</em></strong></a> model of Python in these complex cases.</p><h3>Final Thoughts:</h3><p>A programmer’s goal should be to write clean code that others can understand. I always work at a fast pace. I want to get things done. In this case, I need clarity of my mind, and I find type hints have helped me a lot in providing clarity. It makes me think about the structure of my data and makes it easier for me to figure out what that function is supposed to do. I wrote a couple of months ago. I have made it my habit to write code with type hints, and it makes me feel like a good developer 😎.</p><p>Lastly, I would like to thank you for your precious time. If you have any queries regarding the project, please contact me via this article.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jkishan421/"><strong>LinkedIn</strong></a>.</p><h3>References:</h3><p><a href="https://www.youtube.com/watch?v=dgBCEB2jVU0&amp;ab_channel=ArjanCodes">5_Reasons_why_you_should_use_Type_Hints_in_Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665afa2a4560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Custom Context Manager In Python]]></title>
            <link>https://medium.com/@jkishan421/building-a-custom-context-manager-in-python-940186758606?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/940186758606</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[context-managers]]></category>
            <category><![CDATA[resources]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 12:51:29 GMT</pubDate>
            <atom:updated>2022-12-12T06:57:03.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*jWFZ1uLU4AzTqp9-IXh1VQ.png" /></figure><p>In the world of computers, we regularly come up with the usage of file handling or database connection. In these scenarios, the resources (files, databases) are limited in supply. Hence it is mandatory to release these resources after use. Otherwise, it may cause program crashes or system memory overflow problems. Sometimes as a programmer we forget to free up the resources (file.close(), connection.close()). Therefore we need an <strong><em>automatic mechanism to free up resources</em></strong>. Here comes the role of the python context manager.</p><h3>What is Context Manager?</h3><p>Context manager allows you to <strong>control</strong>, <strong>setup</strong>, and <strong>teardown</strong> any sort of resource in a way that minimizes the chance of you forgetting to do the teardown, especially in the presence of exceptions.</p><h4>Example:</h4><p>If you’ve ever opened the file in python you’ve probably used the <br><strong><em>with-statement </em></strong>to manage the file, this is a context manager, and it is a good example of managing resources because the <strong><em>with-statement</em></strong> automatically closes the file for you when you don’t need it anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07ece3b3d4e7b95c7f7634072fe8b0c5/href">https://medium.com/media/07ece3b3d4e7b95c7f7634072fe8b0c5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/318735b73eeb965a98cfadaced0e5b47/href">https://medium.com/media/318735b73eeb965a98cfadaced0e5b47/href</a></iframe><p>Behind the scene the <strong><em>with-statement</em></strong> uses <strong><em>__enter__()</em></strong> and <strong><em>__exit__()</em></strong> <a href="https://www.geeksforgeeks.org/dunder-magic-methods-python/"><strong>dunder/magic</strong></a><strong> </strong>methods. So in case of exception or code completion, the exit part will execute. You can find more on <strong><em>with-statement</em></strong> <a href="https://www.python.org/dev/peps/pep-0343/"><strong>here</strong></a>.</p><h3>Ways of using Context Manager</h3><h4>1. Normal:</h4><p>Besides opening the file using <strong><em>with-statement</em></strong> you can also <strong><em>handle resources manually</em></strong>. In this way, we don’t use any kind of context manager. We handle the resources by ourselves. Here we open a file in a <strong><em>try block,</em></strong> handle exceptions in <strong><em>except block,</em></strong> and free up resources in the <strong><em>final block.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2098d76f7f0ad637d4cf42d3d74ce8a/href">https://medium.com/media/b2098d76f7f0ad637d4cf42d3d74ce8a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c5cd3394364b27db906cde69539c38/href">https://medium.com/media/09c5cd3394364b27db906cde69539c38/href</a></iframe><h4>2. Build your Context Manager:</h4><p>In this type, we create our class and make it works like a context manager by defining <strong><em>__enter__()</em></strong> and <strong><em>__exit__()</em></strong> methods. After defining these dunder methods (enter, exit) we can use our class with the <strong><em>with-statement</em></strong> of python to automatically teardown the resources.</p><p>Make a class <strong><em>FileManager, </em></strong>define parameterize constructor <strong><em>__init__()</em></strong> that takes filename and mode (read, write, etc) of handling file as arguments. Override a dunder function <strong><em>__enter__()</em></strong> and open the file in it and return the file object. In the last override the <strong><em>__exit__()</em></strong> method and close the file in it. Now our class is ready to be used as a context manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cab5b2f15f630ef6c7bf8fad1854e062/href">https://medium.com/media/cab5b2f15f630ef6c7bf8fad1854e062/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/937b5519b6c9e326daee07930562cd4c/href">https://medium.com/media/937b5519b6c9e326daee07930562cd4c/href</a></iframe><h4>3. Context Manager as a Decorator:</h4><p>Besides a class, we can also <strong><em>make a function to work as a context manager</em></strong>. To achieve this we need to use the <a href="https://docs.python.org/3/library/contextlib.html"><strong>contextlib</strong></a> library of python.</p><p>First of all, write down the definition of the function which opens the file in a <strong><em>try block</em></strong>, and closes the file in the <strong><em>final block</em></strong>. Secondly, attach the decorator of <strong><em>context manager</em></strong> from <a href="https://docs.python.org/3/library/contextlib.html"><strong>contextlib</strong></a> to the function.</p><p>Find more about <strong><em>python</em></strong> <strong><em>decorators</em></strong> <a href="https://www.geeksforgeeks.org/decorators-in-python/"><strong>here</strong></a><strong>.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84cc050c37dead5d4cee6d41ba282ad8/href">https://medium.com/media/84cc050c37dead5d4cee6d41ba282ad8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/038ba2fb75a1348ea9faf1bb8b866211/href">https://medium.com/media/038ba2fb75a1348ea9faf1bb8b866211/href</a></iframe><h3>Conclusion:</h3><p>In this tutorial, we have learned what is context manager, what is the need for it, and how can we use it. We learned how can we make our context manager. We explore the three ways of using a context manager. Firstly, we see the manual way of handling resources using the <strong>try-except-finally block</strong>. Secondly, we <strong><em>make a class that works as a context manager</em></strong>. In last, <strong><em>we make a function that works as a context manager</em></strong> using the <a href="https://docs.python.org/3/library/contextlib.html"><strong>contextlib</strong></a> library of python.</p><p>In the last, I would love to thank you for your precious time. If you have any queries regarding the project you can send me notes on this article.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jai-kishan-ai/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=940186758606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Music Player Application in Python]]></title>
            <link>https://medium.com/@jkishan421/music-player-application-in-python-696d1418e0a6?source=rss-7431ddbc3d22------2</link>
            <guid isPermaLink="false">https://medium.com/p/696d1418e0a6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Jai Kishan]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 13:12:52 GMT</pubDate>
            <atom:updated>2022-02-03T13:12:52.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoGGkmmzve2OU9awSlJFjw.png" /><figcaption>Music Player Application in Python</figcaption></figure><p>In this tutorial, we are going to learn how can we create our Music Player Application in Python. We need the following two python libraries to achieve our goal.</p><ol><li><a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a> [for GUI]</li><li><a href="https://pypi.org/project/pygame/">Pygame</a> [for playing music]</li></ol><h4>The Flow:</h4><p>Firstly we will create a python class for playing music — <strong><em>MusicPlayer, </em></strong>this class is responsible for all the music-related operations such as <strong>playing</strong> the music, <strong>stopping</strong> the music, <strong>pausing</strong> the music, and <strong>setting</strong> the music <strong>volume</strong>.</p><p>Secondly, we need two helper methods <strong>browse_file()</strong>, and <strong>help_me(), </strong>we use these functions to select the music file and show a contact message box to the user respectively.</p><p>Lastly — in the <strong>main()</strong> method — we create the GUI of our Music Player Application using <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>, and enjoy the music🥳.</p><h4>Lets Code:</h4><p><strong><em>Firstly create a MusicPlayer</em></strong> <strong><em>class</em></strong> with play_music(), stop_music(), pause_music(), and set_volume(). As the names suggest these methods are responsible for playing the music, stopping the music, pausing the music, and setting the volume of the music respectively.</p><ol><li><strong>play_music<br></strong>In this method, we first load the music file using <strong>mixer.music.load()</strong> method, then we play the music using <strong>mixer.music.play()</strong> method and in last we set the status to “Music is played”. We also check if music is paused then unpause it using the <strong>mixer.music.unpause()</strong> method.</li><li><strong>stop_music<br></strong>In this method, we stop the selected music using the <strong>mixer.music.stop()</strong> method, and set the status to “Music is stopped”</li><li><strong>pause_music<br></strong>In this method, we declared a global variable PAUSED (used by play_music() method), and set it to True, then we pause the current music using the <strong>mixer.music.pause()</strong> method.</li><li><strong>set_volume<br></strong>In this method, we take the volume value as a function parameter, convert this value to an integer and divide it by 100 (volume can’t exceed 100), then we set the volume of the currently playing music using the <strong>mixer.music.set_volume(vol_value)</strong>.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd64bea0116ca7231238341978da88a2/href">https://medium.com/media/bd64bea0116ca7231238341978da88a2/href</a></iframe><p><strong><em>Secondly, create two methods</em></strong> browse_file() and help_me() for selecting the music file and displaying the help_me message box.</p><ol><li><strong>browse_file<br></strong>In this method, we are loading a music file from our system using <strong>filedialog.askopenfilename()</strong> method from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>.</li><li><strong>help_me<br></strong>In this method, we are displaying the contact us information message box to the user using the <strong>tkinter.messagebox.showinfo()</strong> method from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f5bb5a057d634bcc2dd5290ac1c5cef/href">https://medium.com/media/8f5bb5a057d634bcc2dd5290ac1c5cef/href</a></iframe><p><strong><em>Lastly, create the main method, </em></strong>in this method we are going to create the <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a> window, set its size and title using <strong>window.geometry()</strong> and <strong>window.title()</strong> method respectively. Make the instance of MusicPlayer class. Now create the menu and submenu for the application using the <strong>Menu()</strong> method from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>. These menus are used for selecting the music file. Now create three buttons for play, stop, and pause the music using the <strong>Button()</strong> method, also give an image icon to these buttons using <strong>PhotoImage()</strong> method from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>. Now create the slider to change the volume of the music using the <strong>Scale()</strong> method from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a>. In last set a status using <strong>Label()</strong> from <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a> and start the GUI using <strong>window.mainloop()</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f57a09de27c974dff18b40fdd0a7330/href">https://medium.com/media/1f57a09de27c974dff18b40fdd0a7330/href</a></iframe><h4>The Interface:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*ndeLpuXk9Ypz1uV49DyAFQ.png" /><figcaption>GUI of the application</figcaption></figure><h4>How to Run:</h4><ol><li>Install the <a href="https://pypi.org/project/pygame/">Pygame</a> using <em>`pip install pygame`</em>.</li><li>Select the music file from the menu option of the file on the upper-left corner of the window</li><li>Hit the Play music button</li><li>Enjoy the music 🎵🎶</li></ol><h4>Conclusion</h4><p>In this tutorial, we learned how to create our music player application in python. We used <a href="https://docs.python.org/3/library/tkinter.html">Tkinter</a> and <a href="https://pypi.org/project/pygame/">Pygame</a> for this application. We code our application with GUI, select the music file, and enjoy the music in our application👏.</p><p>In the last, I would love to thank you for your precious time. If you have any queries regarding the project you can send me notes on this article.</p><p>Please find the whole project on my <a href="https://github.com/jaiGit2022/Music-Player-Application"><strong>Github</strong></a> repository.</p><p>For better communication, let’s connect via <a href="https://www.linkedin.com/in/jai-kishan-ai/"><strong>LinkedIn</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=696d1418e0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>