<?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 Kartheek Gottipati on Medium]]></title>
        <description><![CDATA[Stories by Kartheek Gottipati on Medium]]></description>
        <link>https://medium.com/@kartheekgottipati?source=rss-530e34370425------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5TrinTTX378XSS9-6TN-zg.jpeg</url>
            <title>Stories by Kartheek Gottipati on Medium</title>
            <link>https://medium.com/@kartheekgottipati?source=rss-530e34370425------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:48:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartheekgottipati/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[A Deep Dive into Asynchronous Programming in Python]]></title>
            <link>https://medium.com/@kartheekgottipati/a-deep-dive-into-asynchronous-programming-in-python-619577a1cfb6?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/619577a1cfb6</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 06:29:46 GMT</pubDate>
            <atom:updated>2023-07-12T06:31:08.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*PPIp7twJJUknfohZqtL8pQ.png" /></figure><p>Asynchronous programming is a design paradigm that has found a lot of love in the Python community. It’s a fundamental shift in the way we think about programming, enabling us to create more efficient, responsive, and faster applications. This article aims to provide an in-depth look at asynchronous programming in Python, including a host of examples, and to discuss the advantages and disadvantages it brings to Python programming.</p><h3>What is Asynchronous Programming?</h3><p>In traditional synchronous programming, tasks are executed sequentially, one after the other. If a task is waiting for some external resource (like a database query or an API call), the entire program waits and cannot proceed until the resource is returned. This model is easy to understand but can be inefficient.</p><p>Asynchronous programming, on the other hand, allows the execution to proceed without waiting for the resource. If an async task is waiting for an external resource, it can yield control to the system, which can execute other tasks that are ready to run.</p><p>In Python, this is achieved using asyncio, an in-built library for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives. The key components are the async and await keywords, event loops, and coroutines.</p><h3>Understanding the Basics: Async and Await</h3><p>The async and await keywords are the heart of asynchronous programming in Python. They were introduced in Python 3.5 as a part of the asyncio library.</p><p>A function becomes a coroutine when it’s defined using async def. This means it can be paused and resumed at any point in its execution:</p><pre>async def hello_world():<br>    print(&quot;Hello World!&quot;)</pre><p>The await keyword is used in an async function to wait for the completion of the call:</p><pre>async def main():<br>    await hello_world()</pre><p>await can only be used inside async functions and effectively signifies a point where the function will give up control, allowing other tasks to run.</p><p>However, these pieces of code won’t work just by themselves. They need an event loop to be scheduled and run.</p><h3>The Event Loop</h3><p>The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.</p><p>Here’s an example of how to create and manage an event loop:</p><pre>import asyncio<br><br>async def hello_world():<br>    print(&quot;Hello World!&quot;)<br><br>loop = asyncio.get_event_loop()<br>try:<br>    loop.run_until_complete(hello_world())<br>finally:<br>    loop.close()</pre><p>In this example, run_until_complete runs the hello_world coroutine, blocking until it&#39;s finished, and loop.close closes the loop.</p><p>Lets compare the performance while using synchronous vs asynchronous programming.</p><h3>Traditional Synchronous Programming in Python</h3><p>Traditionally, Python is synchronous, which means it executes tasks sequentially. Here’s a simple example of a synchronous program that simulates downloading data from the internet:</p><pre>import time<br><br>def download_data(url):<br>    # Simulate the time taken to download the data<br>    time.sleep(1)<br>    print(f&#39;Downloaded data from {url}&#39;)<br><br>def download_all_data(urls):<br>    for url in urls:<br>        download_data(url)<br><br>urls = [&#39;http://website1.com&#39;, &#39;http://website2.com&#39;, &#39;http://website3.com&#39;]<br>download_all_data(urls)</pre><p>This program works, but it’s not very efficient. Each download_data call waits for one second, simulating the download delay. Our download_all_data function takes 3 seconds in total to complete for 3 websites, even though downloading from different sites could, in theory, be done simultaneously.</p><h3>Asynchronous Programming in Python</h3><p>Asynchronous programming is a different way of structuring code that allows us to do more than one thing at a time. This is incredibly useful when tasks are I/O-bound like in our example above.</p><p>Python introduced keywords async and await in version 3.5 as part of the asyncio library, which provides a foundation for asynchronous programming.</p><p>Let’s rewrite our previous example in an asynchronous style:</p><pre>import asyncio<br><br>async def download_data(url):<br>    # Simulate the time taken to download the data<br>    await asyncio.sleep(1)<br>    print(f&#39;Downloaded data from {url}&#39;)<br><br>async def download_all_data(urls):<br>    tasks = [download_data(url) for url in urls]<br>    await asyncio.gather(*tasks)<br><br>urls = [&#39;http://website1.com&#39;, &#39;http://website2.com&#39;, &#39;http://website3.com&#39;]<br>asyncio.run(download_all_data(urls))</pre><p>In this example, download_data is now a coroutine that can be paused and resumed, allowing other coroutines to run in the meantime. asyncio.gather runs these coroutines concurrently, and asyncio.run is a convenience function that sets up the event loop and runs the main function.</p><p>The async version of our program still ‘downloads’ the data from each URL, but it does all the downloads concurrently. As a result, the async version of our function takes a little over 1 second to run, regardless of the number of URLs.</p><h3>Advantages of Asynchronous Programming</h3><ol><li><strong>Efficiency:</strong> Asynchronous programs are more efficient because they can do other work instead of waiting for I/O operations to complete.</li><li><strong>Performance:</strong> Asynchronous programming can result in significant performance improvements, especially for I/O-bound or network-bound programs.</li><li><strong>Concurrency without threads:</strong> Asynchronous programming in Python allows concurrent execution within a single thread, avoiding overhead associated with multithreading.</li></ol><h3>Disadvantages of Asynchronous Programming</h3><ol><li><strong>Complexity:</strong> Asynchronous code can be more complex to write and understand compared to synchronous code.</li><li><strong>Debugging:</strong> Debugging asynchronous programs can be challenging due to the concurrent execution of tasks.</li><li><strong>CPU-bound tasks:</strong> Asynchronous programming isn’t beneficial for CPU-bound tasks because Python’s Global Interpreter Lock (GIL) prevents it from using multiple cores on a processor.</li><li><strong>Library Support:</strong> Not all Python libraries support asynchronous operations. Using these libraries in an async context could block the event loop, negating the benefits of async programming.</li></ol><h3>Conclusion</h3><p>The journey into asynchronous programming can be a challenging but rewarding endeavor. It might demand a shift in your traditional thinking about how code executes, but once you overcome this, the benefits can be substantial. Whether you’re building a high-performance web server or a system with heavy I/O operations, mastering async programming can give your Python applications a significant performance boost.</p><p>However, it’s important to remember that async isn’t a silver bullet for all situations. It shines in IO-bound scenarios where tasks can be performed concurrently, but in CPU-bound tasks, the advantage is minimal. Additionally, debugging async code and ensuring compatibility with other libraries requires careful consideration.</p><p>As with any tool in your programming toolkit, understanding when and how to use it effectively is the key. Explore, learn, and practice async programming in Python, and you’ll have another powerful approach to solving complex problems efficiently in your developer arsenal. Asynchronous programming doesn’t just make your applications faster; it makes you a more versatile developer, opening the door to new design patterns and solutions.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=619577a1cfb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Corners of Python: 10 Lesser-Known Facts about the Beloved Language]]></title>
            <link>https://medium.com/@kartheekgottipati/the-hidden-corners-of-python-10-lesser-known-facts-about-the-beloved-language-8636b1453440?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/8636b1453440</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[guido-van-rossum]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:18:46 GMT</pubDate>
            <atom:updated>2023-07-11T08:18:46.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*PPIp7twJJUknfohZqtL8pQ.png" /></figure><p>Python, the renowned high-level programming language, has seen a meteoric rise since its inception. Known for its simplicity, flexibility, and power, Python is a favorite among beginners and seasoned developers alike. However, there’s more to this language than meets the eye. In this post, we uncover some fascinating Python trivia that you might not have come across.</p><h3>1. The Monty Python Connection</h3><p>Did you know that Python isn’t named after the slithery reptile? Instead, it draws its name from the British comedy series, “Monty Python’s Flying Circus”. Guido van Rossum, Python’s creator, wanted to signify that Python was fun to work with. Thus, the language takes its moniker from van Rossum’s favorite TV show.</p><h3>2. The Zen of Python: Python’s Philosophical Guideline</h3><p>Python isn’t just a programming language; it has its own philosophy. The Zen of Python, accessible by typing import this into the Python interpreter, is a collection of 19 aphorisms that serve as guiding principles for writing Pythonic code. These guidelines champion simplicity, clarity, and minimalism, underlining Python&#39;s core philosophies.</p><h3>3. Python’s Longevity</h3><p>Python has been around longer than most might realize. Guido van Rossum began developing the language in December 1989, and the first version was released to the public in February 1991. This makes Python one of the oldest high-level languages still in widespread use today.</p><h3>4. The Print Statement vs. Function</h3><p>A notable syntactical change occurred between Python 2 and 3 with the print statement becoming a function. Instead of print &quot;Hello, world!&quot;, Python 3 adopted print(&quot;Hello, world!&quot;). This change, among others, marks the clear distinction between Python 2 and 3.</p><h3>5. The Benevolent Dictator For Life (BDFL)</h3><p>Guido van Rossum was affectionately known as the BDFL, or Benevolent Dictator For Life, by the Python community. This title symbolized his ultimate authority in deciding the trajectory of Python’s development. However, in July 2018, van Rossum stepped down from this position, marking the end of an era.</p><h3>6. The Global Interpreter Lock (GIL)</h3><p>Python employs a Global Interpreter Lock (GIL), preventing multiple native threads from executing Python bytecodes simultaneously. While the GIL simplifies many programming aspects and contributes to Python’s user-friendliness, it also serves as a bottleneck for multi-threaded programs.</p><h3>7. The “Pythonic” Way</h3><p>The term “Pythonic” isn’t just a descriptor; it’s a standard in the Python community. “Pythonic” code adheres to the idiomatic conventions of the Python language, which means it’s readable, clear, and efficient. The term embodies the essence of Python’s philosophical approach to coding.</p><h3>8. Python Enhancement Proposals (PEPs)</h3><p>Python’s development and progression occur through Python Enhancement Proposals or PEPs. PEPs propose and document new features, collect community inputs, and record the design decisions of Python. The most famous PEP is undoubtedly PEP 8, Python’s style guide.</p><h3>9. Python’s Influence on Other Languages</h3><p>Python’s influence extends beyond its own community. The language’s design philosophy and syntax have played a crucial role in shaping other programming languages, including Go, Ruby, Swift, and Julia.</p><h3>10. Python and Google</h3><p>Google’s relationship with Python is more intimate than you might think. In the early 2000s, Google made a considerable investment in Python, and it is now one of the official server-side languages at Google, alongside Java and Go. Python’s creator, Guido van Rossum, even spent several years at Google, guiding Python’s development.</p><h3>Conclusion</h3><p>The story of Python is one of constant evolution, widespread influence, and a testament to the power of simplicity and clarity in code. As Python continues to grow and mature, it remains, above all, a language that brings joy to those who use it, much like the comedy troupe it was named after.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8636b1453440" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring PEP 8 Compliance: Tools for Automating Adherence to Coding Standards]]></title>
            <link>https://medium.com/@kartheekgottipati/ensuring-pep-8-compliance-tools-for-automating-adherence-to-coding-standards-5a6cc2f48519?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a6cc2f48519</guid>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[linting]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-standards-python]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 02:00:09 GMT</pubDate>
            <atom:updated>2023-07-11T02:00:09.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*PPIp7twJJUknfohZqtL8pQ.png" /></figure><p>Writing Python code that is both efficient and easy to understand is an essential aspect of development. Maintaining strict coding standards improves the code’s readability and manageability, making collaborative development smoother and more productive. Python’s primary coding standard is the PEP 8 style guide, a Python Enhancement Proposal detailing a set of recommendations for Python code writing.</p><p>In this blog post, we will discuss how to use various tools to automate your code’s compliance with the PEP 8 guidelines and other good coding practices. The tools we’ll cover include flake8, black, isort, and mypy.</p><h3>Flake8 for Code Linting</h3><p>Flake8 is a robust tool that checks your Python code against the PEP 8 style guide, catches programming errors, and even identifies code complexity issues. It’s a great tool to have in your arsenal for maintaining clean, professional code.</p><p>Install Flake8 using pip:</p><pre>pip install flake8</pre><p>To lint your code with Flake8, navigate to your project directory in the terminal and type:</p><pre>flake8 .</pre><p>You can customize Flake8’s behavior with a .flake8 configuration file at your project&#39;s root.</p><h3>Black for Code Formatting</h3><p>Black is a code formatter that enforces readability standards by automatically reformatting your code. It is often described as “uncompromising” because it strictly enforces a single, consistent style.</p><p>To install Black, use pip:</p><pre>pip install black</pre><p>To format your code using Black, navigate to your project’s root in the terminal and type:</p><pre>black </pre><p>Black’s behavior can be configured using a pyproject.toml file.</p><h3>iSort for Import Sorting</h3><p>iSort is a utility that automatically sorts your imports alphabetically and separates them into sections and types, enhancing the readability of your code.</p><p>Install iSort using pip:</p><pre>pip install isort</pre><p>To sort your imports, navigate to your project’s root in the terminal and type:</p><pre>isort .</pre><p>Like Black, iSort can also be configured via a pyproject.toml file.</p><h3>Mypy for Static Type Checking</h3><p>While Python is dynamically typed, Mypy introduces static type checking, combining the advantages of both dynamic and static typing. This adds an extra layer of reliability to your code.</p><p>To install Mypy, use pip:</p><pre>pip install mypy</pre><p>To run Mypy on your code, navigate to your project’s root in the terminal and type:</p><pre>mypy .</pre><p>Customize Mypy’s behavior with a mypy.ini configuration file at your project&#39;s root.</p><h3>Integrating with Pre-Commit for Automated Checks</h3><p>Pre-commit is a framework for managing and maintaining pre-commit hooks. These hooks are scripts that run automatically before each git commit, checking for any issues in the code. To ensure the tools we&#39;ve discussed are run before each commit, we can integrate them into pre-commit hooks.</p><p>First, install pre-commit via pip:</p><pre>pip install pre-commit</pre><p>Next, create a .pre-commit-config.yaml file at your project&#39;s root. This is where you&#39;ll specify the tools (repos) to be used, along with their versions (rev) and hooks (id). A basic configuration might look like this:</p><pre>repos:<br>  - repo: https://github.com/ambv/black<br>    rev: stable<br>    hooks:<br>      - id: black<br>        language_version: python3.6<br>  - repo: https://github.com/pycqa/isort<br>    rev: 5.6.4<br>    hooks:<br>      - id: isort<br>  - repo: https://github.com/PyCQA/flake8<br>    rev: 3.8.4<br>    hooks:<br>      - id: flake8<br>  - repo: https://github.com/python/mypy<br>    rev: v0.790<br>    hooks:<br>      - id: mypy</pre><p>Finally, in the terminal, navigate to your project’s root and run:</p><pre>pre-commit install</pre><p>This command sets up the pre-commit framework in your repository. Now, before each commit, the specified tools will run checks on your code. If any tool identifies issues, the commit is aborted, and you’re prompted to fix the issues before committing again.</p><h3>Conclusion</h3><p>By integrating these tools into your workflow, you’re taking a significant step toward consistently maintaining high-quality Python code that adheres strictly to established coding standards.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a6cc2f48519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Multi-Architecture Build Images with Docker]]></title>
            <link>https://medium.com/@kartheekgottipati/creating-multi-architecture-build-images-with-docker-8e3208490a2a?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3208490a2a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[build]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 01:38:47 GMT</pubDate>
            <atom:updated>2023-07-11T01:38:47.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Uqd2iSZRO9hxAAN0cTHJw.png" /></figure><p>Docker has become a staple in the software development ecosystem, especially for developers who need to package and distribute their applications uniformly, irrespective of the environment. However, as we step into the era of diverse hardware architectures, a new challenge emerges: how can we create Docker images that work seamlessly across multiple architectures?</p><p>Thankfully, Docker has introduced multi-architecture build capabilities, which allow developers to build Docker images that can run on different hardware architectures like amd64, arm64 etc. This feature uses a concept called &quot;manifest lists,&quot; also known as &quot;multi-architecture images.&quot; In this blog post, we&#39;ll explore this concept in detail and provide step-by-step instructions on creating multi-architecture build images with Docker.</p><h3>What are Multi-Architecture Images?</h3><p>In the Docker world, a manifest is a list that can point to image layers created for different architectures. When a Docker pull command is executed, Docker will check the manifest and download the appropriate image layers for the host’s architecture. In simple terms, it is a single Docker image tag that encapsulates multiple images for different architectures.</p><h3>Prerequisites</h3><p>To follow along with this guide, you’ll need to have:</p><ol><li>Docker installed on your machine. You can download Docker <a href="https://www.docker.com/products/docker-desktop">here</a>.</li><li>Docker Buildx installed and enabled. Buildx, a Docker CLI plugin, is bundled with Docker 19.03 and later. It comes with support for the new features of the BuildKit builder toolkit. It also provides the same user experience as docker build and supports several new features.</li></ol><p>Let’s get started!</p><h3>Step 1: Check Docker Buildx Installation</h3><p>Ensure you have Docker Buildx installed by running the following command:</p><pre>docker buildx version</pre><p>If Docker Buildx is installed properly, you should see the version of Buildx.</p><h3>Step 2: Create a New Builder Instance</h3><p>A builder instance in Docker represents a build environment. To use the multi-architecture build capabilities, we need to create and switch to a new instance of the builder. Use the following commands:</p><pre>docker buildx create --use --name mybuilder</pre><p>This command creates a new builder instance named “mybuilder” and switches to it.</p><h3>Step 3: Inspect the Builder Instance</h3><p>You can use the inspect sub-command to verify the current builder instance and its capabilities:</p><pre>docker buildx inspect --bootstrap</pre><p>In the output, under the “Platforms” section, you should see multiple architectures listed, like amd64, arm64, etc.</p><h3>Step 4: Create a Multi-Architecture Docker Image</h3><p>To demonstrate this, let’s create a simple Dockerfile. This Dockerfile uses the official Node.js Alpine image as the base image and runs a simple script.</p><p>Here’s what the Dockerfile looks like:</p><pre># Dockerfile<br>FROM node:alpine<br>WORKDIR /app<br>COPY . .<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>Assume we have a simple index.js file in the same directory:</p><pre>// index.js<br>console.log(&#39;Hello, Docker!&#39;);</pre><p>Now, let’s build the Docker image for multiple architectures:</p><pre>docker buildx build --platform linux/amd64,linux/arm64 -t username/multiarch-image:latest --push .</pre><p>This command tells Docker to build the image for both amd64 and arm64 architectures, tag it with the specified tag, and push it to the Docker registry.</p><h3>Wrapping Up</h3><p>In this blog post, we’ve explored Docker’s multi-architecture build capabilities, which help create images that can run seamlessly across different architectures. Using Docker’s Buildx CLI plugin, we’ve demonstrated how to create a Docker image for two different architectures.</p><p>Remember, while this feature is incredibly useful for creating portable applications, it also requires more computational resources to build and store the images. Therefore, it’s wise to use multi-architecture builds only when you need your application to be architecture-agnostic.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3208490a2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Lean Containers: Advanced Techniques for Docker Image Optimization]]></title>
            <link>https://medium.com/@kartheekgottipati/building-lean-containers-advanced-techniques-for-docker-image-optimization-c1ada16b7ac1?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1ada16b7ac1</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 01:27:23 GMT</pubDate>
            <atom:updated>2023-07-11T01:39:17.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Uqd2iSZRO9hxAAN0cTHJw.png" /></figure><p>Docker has revolutionized how we develop and deploy applications. It provides a standardized way to package an application along with its runtime dependencies so that it can run anywhere, regardless of the environment. However, as with any tool, it can be used effectively or ineffectively. Large Docker images can consume significant storage and network resources, slow down deployments, and increase security risks. This blog post explores the optimization of Docker images for faster, leaner deployments.</p><p><em>Note: This guide assumes that you are familiar with Docker and Dockerfile basics.</em></p><h3>Start with the Right Base Image</h3><p>The base image is the foundation on which your Docker image is built. It’s crucial to choose a small, secure base image. A minimal base image like alpine is a good place to start as it&#39;s only about 5MB.</p><pre>FROM alpine:latest</pre><p>The trade-off is that alpine images use musl libc instead of glibc, which can cause compatibility issues with certain software. If you need a glibc-based image, consider using debian:slim or ubuntu:slim instead.</p><p>Remember to tag your base images appropriately to avoid breaking your build when the latest tag changes.</p><h3>Multi-Stage Builds</h3><p>Multi-stage builds are a Docker feature that help you reduce the size of your final Docker image by discarding unnecessary artifacts and dependencies. Let’s see this in action with a Python application:</p><pre># Stage 1: build the application<br>FROM python:3.9-slim as builder<br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br>RUN python -m unittest discover<br><br># Stage 2: create a clean image<br>FROM python:3.9-slim<br>COPY --from=builder /app /app<br><br>WORKDIR /app<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>In this multi-stage build process, the final Docker image only contains the Python runtime, the application, and its necessary dependencies, omitting build tools and test artifacts.</p><h3>Consolidating Docker Layers</h3><p>Every command in a Dockerfile contributes to a new layer in the image. Although Docker tries to reuse layers when possible, combining multiple commands into one can significantly cut down the layer count.</p><p>Instead of having separate RUN commands as shown below:</p><pre>RUN apt-get update<br>RUN apt-get install -y curl<br>RUN apt-get install -y vim<br>RUN apt-get clean</pre><p>You can consolidate these commands into a single layer:</p><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br>    curl \<br>    vim \<br> &amp;&amp; apt-get clean</pre><h3>Cleaning Up Post-Installation</h3><p>Package managers often leave behind cache files, which unnecessarily inflate the Docker image size. You can remove these files within the same RUN command:</p><pre>RUN apt-get update &amp;&amp; apt-get install -y \<br>    curl \<br>    vim \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>Here, rm -rf /var/lib/apt/lists/* gets rid of APT&#39;s package cache.</p><h3>Exclude Unnecessary Files</h3><p>A .dockerignore file helps to prevent unwanted files from being added to your Docker image. The format of .dockerignore is similar to .gitignore.</p><p>Here is a sample .dockerignore file:</p><pre>.git<br>Dockerfile<br>README.md<br>*.log</pre><h3>Making the Most of Docker’s Build Cache</h3><p>Docker attempts to cache intermediate layers to speed up subsequent builds. But for a cache to be reusable, all previous steps need to be identical. Hence, it’s advisable to order Dockerfile commands from the least frequently changed to the most frequently changed.</p><pre># These steps don&#39;t change often<br>FROM node:14<br>WORKDIR /app<br>COPY package.json yarn.lock ./<br><br># Install dependencies<br>RUN yarn install<br><br># These steps change frequently<br>COPY . .<br>RUN yarn build</pre><p>In this case, code changes won’t invalidate the yarn install cache, improving the build time.</p><h3>Conclusion</h3><p>Optimizing Docker images is a crucial aspect of leveraging Docker’s full potential. By implementing the strategies outlined in this guide — selecting the correct base image, using multi-stage builds, minimizing Docker layers, cleaning up post-installation, excluding unnecessary files, and effectively using Docker’s build cache — you can significantly reduce the size and build time of your Docker images.</p><p>Optimized Docker images lead to faster, more secure deployments, reduced resource consumption, and a more efficient development workflow. Remember, creating efficient Docker images isn’t a one-off task but an ongoing practice that you should embed in your CI/CD pipeline. Keep refining, and enjoy your journey with Docker!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ada16b7ac1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Gotchas: Unexpected Snags and How to Handle Them]]></title>
            <link>https://medium.com/@kartheekgottipati/python-gotchas-unexpected-snags-and-how-to-handle-them-3211ff499b00?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/3211ff499b00</guid>
            <category><![CDATA[gotchas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 22:58:45 GMT</pubDate>
            <atom:updated>2023-07-10T22:58:45.526Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is revered for its readability and simplicity, making it a popular choice for beginners and experts alike. However, just like any other programming language, Python has its share of quirks or “gotchas” — unexpected behaviors that can stump programmers, particularly those who are new to the language. In this blog post, we’ll take a look at some of the most common Python gotchas and discuss how to handle them.</p><h3>Mutable Default Arguments</h3><p>In Python, function arguments are evaluated once when the function is defined, not each time the function is called. This means mutable default arguments can lead to unexpected behavior:</p><pre>def append_to_list(value, my_list=[]):<br>    my_list.append(value)<br>    return my_list<br><br>print(append_to_list(1))  # Output: [1]<br>print(append_to_list(2))  # Output: [1, 2]</pre><p>You might expect the second call to return [2], but it returns [1, 2] because the list my_list is created only once. To avoid this, you can use None as the default value and then initialize my_list in the function body. Here are two methods to handle this:</p><h4>Using an explicit if statement:</h4><pre>def append_to_list(value, my_list=None):<br>    if my_list is None:<br>        my_list = []<br>    my_list.append(value)<br>    return my_list<br><br>print(append_to_list(1))  # Output: [1]<br>print(append_to_list(2))  # Output: [2]</pre><h4>Using Python’s Truthy and Falsy values:</h4><pre>def append_to_list(value, my_list=None):<br>    my_list = my_list or []<br>    my_list.append(value)<br>    return my_list<br><br>print(append_to_list(1))  # Output: [1]<br>print(append_to_list(2))  # Output: [2]</pre><p>While the if statement is more explicit and may be clearer for beginners or developers coming from other languages, using my_list = my_list or [] is a more concise, &quot;Pythonic&quot; way of handling this scenario. This idiom leverages Python&#39;s handling of truthy and falsy values: an empty list, an empty dictionary, None, False, 0, and empty strings all evaluate to False in a boolean context, allowing the or operator to provide a default value when my_list is None.</p><h3>Variable Scoping — Global vs Local</h3><p>In Python, variables referenced inside a function are considered local to that function unless explicitly declared as global. This can lead to unexpected results:</p><pre>x = 10<br><br>def modify_global():<br>    x += 5<br>    return x<br><br>print(modify_global())  # UnboundLocalError: local variable &#39;x&#39; referenced before assignment</pre><p>To avoid this error, you can declare x as global inside the function:</p><pre>x = 10<br><br>def modify_global():<br>    global x<br>    x += 5<br>    return x<br><br>print(modify_global())  # Output: 15</pre><h3>Variable Leaking in List Comprehensions</h3><p>In Python 2, the iteration variable in list comprehensions leaks into the global namespace, which can lead to confusing results. However, this is fixed in Python 3:</p><pre># Python 2<br>x = &#39;Before&#39;<br>dummy = [x for x in range(5)]<br>print(x)  # Output: 4<br><br># Python 3<br>x = &#39;Before&#39;<br>dummy = [x for x in range(5)]<br>print(x)  # Output: &#39;Before&#39;</pre><p>If you’re still working in Python 2, be aware of this and consider using a different variable name in the comprehension.</p><h3>Equality vs Identity</h3><p>In Python, == checks for equality (do two objects have the same value?), while is checks for identity (are two names or variables actually the same object?). This can lead to some surprises:</p><pre>x = [1, 2, 3]<br>y = [1, 2, 3]<br><br>print(x == y)  # Output: True<br>print(x is y)  # Output: False</pre><p>Both x and y have the same values, but they are not the same object, leading to the difference in output. Use == when you want to compare values and is when you want to check if two variables point to the same object.</p><h3>Division Operator</h3><p>Python’s behavior for division is different depending on the version. In Python 2, dividing two integers results in an integer (floor division), while in Python 3, it results in a float. This can cause unexpected results if you are not aware of it:</p><pre># Python 2<br>print(5 / 2)  # Output: 2<br><br># Python 3<br>print(5 / 2)  # Output: 2.5</pre><p>In Python 2, to get the floating-point division, you can import division from __future__, or convert one of the operands to a float. In Python 3, to get the floor division, use //.</p><h3>Conclusion</h3><p>Every language has its share of quirks and Python is no different. Being aware of these can help you avoid hours of debugging. Python’s surprises usually result from the language’s design principles and features, and once you get to know them, they can often be used to your advantage. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3211ff499b00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switch Case in Python: Simulating the Classic Control Structure]]></title>
            <link>https://medium.com/@kartheekgottipati/switch-case-in-python-simulating-the-classic-control-structure-d32100219791?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/d32100219791</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[switch-case]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 22:40:57 GMT</pubDate>
            <atom:updated>2023-07-10T22:40:57.096Z</atom:updated>
            <content:encoded><![CDATA[<p>In a majority of programming languages like C, Java, and JavaScript, one of the most common decision-making structures is the “switch-case” statement. It allows a variable to be tested for equality against a list of values, with each value having its own code block.</p><p>However, those who are new to Python may be surprised to learn that Python doesn’t have a built-in “switch-case” statement. This is by design, because Python’s philosophy leans towards simplicity and readability, and switch cases can often be replaced by more “Pythonic” structures, such as dictionaries and function mappings.</p><p>Even though Python does not offer a built-in switch-case construct, you can easily simulate it using either if-elif-else blocks, dictionaries, or classes. This blog post will show you how to accomplish this.</p><h3>Using if-elif-else</h3><p>The simplest way to implement a switch-case mechanism in Python is through the if-elif-else statement. Here’s an example:</p><pre>def switch_case(value):<br>    if value == &quot;case1&quot;:<br>        return &quot;You selected case 1&quot;<br>    elif value == &quot;case2&quot;:<br>        return &quot;You selected case 2&quot;<br>    else:<br>        return &quot;Invalid case&quot;<br><br>print(switch_case(&quot;case1&quot;))  # Output: You selected case 1<br>print(switch_case(&quot;case3&quot;))  # Output: Invalid case</pre><p>While this approach is straightforward, it can get unwieldy if there are a large number of cases, leading to a long and potentially confusing code block.</p><h3>Using Dictionaries</h3><p>Another method to simulate a switch-case in Python is by using dictionaries. Dictionaries in Python are a collection of key-value pairs. The “case” becomes the key, and the result or function becomes the value. Here’s how you can implement it:</p><pre>def switch_case(value):<br>    return {<br>        &quot;case1&quot;: &quot;You selected case 1&quot;,<br>        &quot;case2&quot;: &quot;You selected case 2&quot;<br>    }.get(value, &quot;Invalid case&quot;)<br><br>print(switch_case(&quot;case1&quot;))  # Output: You selected case 1<br>print(switch_case(&quot;case3&quot;))  # Output: Invalid case</pre><p>In the code above, we use the get() method that dictionaries provide. This method returns the value for a given key if it exists, otherwise it returns a default value.</p><p>This approach is more efficient and scalable for a large number of cases compared to if-elif-else, especially when the case outcomes are static and do not depend on complex computation or conditional logic.</p><h3>Using Function Mapping</h3><p>In case where each “case” needs to perform more complex operations, we can take advantage of Python’s first-class functions and use a dictionary to map “cases” to functions. Here’s how you can implement it:</p><pre>def case1():<br>    return &quot;You selected case 1&quot;<br><br>def case2():<br>    return &quot;You selected case 2&quot;<br><br>def default():<br>    return &quot;Invalid case&quot;<br><br>def switch_case(value):<br>    return {<br>        &quot;case1&quot;: case1,<br>        &quot;case2&quot;: case2<br>    }.get(value, default)()<br><br>print(switch_case(&quot;case1&quot;))  # Output: You selected case 1<br>print(switch_case(&quot;case3&quot;))  # Output: Invalid case</pre><p>This approach allows you to encapsulate more complex code within each function and keeps the switch case construct clean and easy to read.</p><h3>Conclusion</h3><p>Although Python does not have a built-in switch-case structure, it provides other more flexible constructs like dictionaries and function mappings to get the job done. Depending on your use case, you can choose the best approach to simulate a switch-case in Python.</p><p>The lack of a switch-case structure is a testament to Python’s commitment to readability and simplicity. It encourages you to think about alternative ways to achieve the same result. With Python, you always have a variety of tools at your disposal to tackle any problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32100219791" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying AWS Lambda Functions — Deployment Package vs Docker Containers]]></title>
            <link>https://medium.com/@kartheekgottipati/deploying-aws-lambda-functions-deployment-package-vs-docker-containers-2f624e4bd0a5?source=rss-530e34370425------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f624e4bd0a5</guid>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Kartheek Gottipati]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 14:38:56 GMT</pubDate>
            <atom:updated>2023-07-10T14:41:35.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying AWS Lambda Functions — Deployment Package vs Docker Containers</h3><p>Today, we will be diving deep into the realm of AWS Lambda functions. We’ll explore two prominent deployment options: the classic AWS Lambda Deployment Package and the contemporary use of Docker Containers. By comparing these two, we hope to equip you with a clearer perspective on which strategy best suits your specific use case.</p><h3>What are AWS Lambda Functions?</h3><p>Before we compare the deployment methods, let’s remind ourselves what AWS Lambda is. AWS Lambda is a Serverless computing service provided by Amazon Web Services. It allows you to run your code without provisioning or managing servers. You simply upload your code (in a format known as a ‘Lambda function’), and Lambda takes care of everything required to run and scale your code with high availability.</p><h3>The Deployment Package</h3><p>Traditionally, AWS Lambda functions were deployed using a zip file, known as a deployment package. This package contained your code and any dependencies it required. This was then uploaded directly to AWS Lambda or via Amazon S3.</p><h4>Advantages of Deployment Packages</h4><ol><li><strong>Simplicity:</strong> Deployment packages are simple and easy to create. If your application has few dependencies, it is often quicker to deploy your function using this method.</li><li><strong>Language Support:</strong> AWS Lambda supports multiple coding languages such as Python, Node.js, Java, and many more. These diverse options give developers greater flexibility.</li><li><strong>Speed:</strong> Deployment packages can be faster to upload and deploy, especially for smaller code bases.</li></ol><h4>Drawbacks of Deployment Packages</h4><ol><li><strong>Dependency Management:</strong> If your application has a complex array of dependencies, creating a deployment package can be time-consuming and error-prone.</li><li><strong>Runtime Limitations:</strong> With a deployment package, you’re limited to the runtimes AWS Lambda provides.</li></ol><h3>Docker Containers</h3><p>In late 2020, AWS introduced the capability to package and deploy Lambda functions as container images. With support for images of up to 10GB, this method allows developers to include large dependencies and libraries much more easily.</p><h4>Advantages of Docker Containers</h4><ol><li><strong>Portable:</strong> Docker containers can be run anywhere Docker is supported, providing a consistent environment for development and testing.</li><li><strong>Improved Dependency Management:</strong> With Docker, you can manage complex dependencies more efficiently. Docker’s layered approach to images also means you can share common dependencies between images, reducing the overall size and deployment time.</li><li><strong>Larger Codebases and Dependencies:</strong> AWS supports Docker images up to 10GB, allowing for much larger applications and dependencies than the 250MB (unzipped) limit for traditional deployment packages.</li><li><strong>Custom Runtimes:</strong> With Docker, you aren’t limited to the runtimes AWS provides. You can create a custom runtime, giving you greater control over the environment in which your function runs.</li></ol><h4>Drawbacks of Docker Containers</h4><ol><li><strong>Complexity:</strong> Docker has a steeper learning curve than deployment packages, particularly if you’re new to containers.</li><li><strong>Speed:</strong> Depending on the size of your container, deployment could be slower than a deployment package.</li></ol><h3>The Verdict: Which Should You Use?</h3><p>The choice between a deployment package and a Docker container largely depends on your application’s requirements and your team’s familiarity with Docker.</p><p>If your team is comfortable with Docker and your application has a large number of dependencies or requires a custom runtime, Docker containers are likely your best option. The increased codebase size limit and improved dependency management can significantly simplify your deployment process.</p><p>On the other hand, if your application is relatively straightforward with few dependencies, or if your team isn’t familiar with Docker, a deployment package may be a more suitable choice. Its simplicity and speed can help you get your application up and running quickly.</p><p>Both deployment methods offer their unique advantages. Take the time to understand the needs of your project and team before deciding on the method to use. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f624e4bd0a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>