<?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 Wazed Khan on Medium]]></title>
        <description><![CDATA[Stories by Wazed Khan on Medium]]></description>
        <link>https://medium.com/@wajedkhan?source=rss-a27e5195dae8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KAAyUcDY8bmFE6ekTmylBg.jpeg</url>
            <title>Stories by Wazed Khan on Medium</title>
            <link>https://medium.com/@wajedkhan?source=rss-a27e5195dae8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:13:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wajedkhan/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[How to Implement Graceful Shutdown in a Go HTTP Server (Step by Step)]]></title>
            <link>https://wajedkhan.medium.com/how-to-implement-graceful-shutdown-in-a-go-http-server-step-by-step-555329cda4fb?source=rss-a27e5195dae8------2</link>
            <guid isPermaLink="false">https://medium.com/p/555329cda4fb</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Wazed Khan]]></dc:creator>
            <pubDate>Tue, 19 May 2026 19:11:14 GMT</pubDate>
            <atom:updated>2026-05-19T19:12:38.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0UH1osk34KqgPtjT3pQTQ.png" /><figcaption>go gracful shutdonw</figcaption></figure><p>Why Go HTTP servers drop requests on Ctrl+C, how OS signals work in Go, how to properly shut down an HTTP server without losing in-flight requests, and how to design middleware-based request tracking using sync.WaitGroup. You will also learn how to handle a second Ctrl+C as a force kill for real production scenarios.</p><p>Every step includes working code and a practical mental model you can apply in real backend systems.</p><h3>Table of Contents</h3><ul><li>What is graceful shutdown and why it matters</li><li>The problem with a naive Go HTTP server</li><li>Step 1: Catch the OS signal</li><li>Step 2: Run the server in a goroutine</li><li>Step 3 : Call srv.Shutdown()</li><li>Step 4: The fixed timeout problem</li><li>Step 5:WaitGroup: let the server tell you when it&#39;s done</li><li>Step 6: Keep handlers clean with middleware</li><li>Step 7: Second Ctrl+C as force kill with signal.NotifyContext</li><li>Step 8: Make handlers respect shutdown via r.Context()</li><li>Complete production-ready example</li><li>Kubernetes and terminationGracePeriodSeconds</li><li>Summary</li></ul><h3>What is graceful shutdown and why does it matter? {#what-is-graceful-shutdown}</h3><p>When you hit Ctrl+C on a running Go server, the OS sends a SIGINT signal. By default, the process dies immediately mid-request, mid-write, mid-database-transaction. The client on the other end gets a connection reset error.</p><p>Think of it like a restaurant. A customer just ordered food and the waiter is halfway through writing the order. The manager yells “EVERYONE OUT NOW.” The waiter drops the pen. The customer gets nothing.</p><p><strong>Graceful shutdown</strong> is the polite version. The manager says: “Stop taking new orders, but finish the ones already started.” Every in-flight request completes. The client gets a proper response. The server exits cleanly.</p><p>This matters in production for three reasons:</p><ul><li><strong>Data integrity: </strong>a request interrupted mid-write can leave our database or file system in a corrupt state.</li><li><strong>User experience: </strong>clients see errors they shouldn’t see, and often retry, causing duplicate work.</li><li><strong>Kubernetes and rolling deploys: </strong>without graceful shutdown, every deploy drops requests. With it, deploys are invisible to users.</li></ul><h3>The problem with the naive Go server {#the-naive-approach}</h3><p>Most Go tutorials start with something like this:</p><pre>func main() {<br>    mux := http.NewServeMux()<br>    mux.HandleFunc(&quot;/api/set&quot;, handler.Set)<br>    log.Fatal(http.ListenAndServe(&quot;:8000&quot;, mux))<br>}</pre><p>For local development, it works. But in production, this version has an important <strong>limitation</strong>: <br>it does not support graceful shutdown. That becomes a problem when the application is restarted, redeployed, crashes, or receives a termination signal from systems like Kubernetes. From the restaurant scenario earlier, imagine the manager suddenly walks in and shouts:</p><blockquote><em>“EVERYONE OUT. RIGHT NOW.”</em></blockquote><p>Customers still eating? Out. <br>Someone waiting for their food? Out.<br>A waiter carrying dishes to a table? Doesn’t matter. Out.<br>No one gets time to finish what they started.</p><p>In our case, the restaurant is our server, the customers are incoming requests, and the manager shouting “everyone out” is our application process shutting down immediately.</p><p>Without graceful shutdown:<br>- active requests can get interrupted<br>- clients may see connection errors or timeouts<br>- deployments can drop user requests<br>- ongoing writes may stop midway, creating data consistency risks</p><p>The server does not pause and say:</p><blockquote><em>“No new customers. Let the current ones finish first.”</em></blockquote><p>It simply stops.<br>That might be acceptable during local development, but production systems need reliability and safe handling of in-progress work. Graceful shutdown helps the application exit cleanly instead of leaving users and sometimes data in an unexpected state.</p><h3>Step 1: Catch the OS Signal {#step-1-catch-the-signal}</h3><p>In this step, we need to talk briefly about signals. If you are not familiar with them, don’t worry we will keep it lightweight. It is still worth taking a quick look at the package documentation: <a href="https://pkg.go.dev/os/signal">https://pkg.go.dev/os/signal</a></p><p>Going back to our restaurant example: we already learned that we cannot simply shout:</p><blockquote><em>“EVERYONE OUT. RIGHT NOW.”</em></blockquote><p>We know the consequences of that approach.</p><p>So we need something customers do not know about, but restaurant staff are trained to understand and react to.</p><p>Imagine the manager has an internal emergency instruction shared only with staff members. Once staff receive it:</p><ul><li>stop taking new customers</li><li>prepare for closing</li><li>let ongoing work finish safely</li></ul><p>In Go, we do not have to create this signaling system ourselves operating systems already provide signals. Our job is simply to listen for them and react appropriately.</p><p>Let’s look at the code:</p><pre>quit := make(chan os.Signal, 1)<br>signal.Notify(<br>    quit,<br>    syscall.SIGINT,<br>    syscall.SIGTERM,<br>)<br>&lt;-quit<br>fmt.Println(&quot;signal received, shutting down...&quot;)</pre><p>What is happening here?</p><pre>signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)</pre><p>This tells Go:</p><blockquote><em>“When these operating system signals arrive, do not terminate immediately. Send them to this channel so we can decide how to shut down.”</em></blockquote><p>Then this line:</p><pre>&lt;-quit</pre><p>blocks the main goroutine and waits until one of those signals arrives.</p><h3>SIGINT vs SIGTERM</h3><ul><li>SIGINT → usually sent when pressing Ctrl + C</li><li>SIGTERM → commonly sent by kill commands and orchestration systems like Kubernetes during deployments or pod shutdowns</li></ul><p>In production systems, handling both is common practice. But there is still a problem. Our current server uses:</p><pre>log.Fatal(http.ListenAndServe(&quot;:8000&quot;, mux))</pre><p>ListenAndServe() blocks the main goroutine.</p><p>That means execution never reaches our signal handling code because Go executes code from top to bottom, and ListenAndServe() is a blocking call. Once it starts the server, it keeps running and holds the main goroutine there, preventing execution from moving to the signal handling logic below.<br>It is like teaching restaurant staff the emergency closing procedure but locking them in the kitchen so they never hear the announcement.<br>We need one more step to make this work properly.</p><h3>Step 2: Run the Server in a Goroutine {#step-2-goroutine}</h3><p>In the previous step, we learned that ListenAndServe() blocks the main goroutine.</p><p>That means our restaurant staff know the emergency procedure, but nobody is actually listening for the manager’s instruction because everyone is busy serving customers.<br>We need someone whose only job is to stay alert and listen for shutdown instructions.</p><p>This is where goroutines help.<br>If you are new to goroutines, think of them as lightweight workers managed by Go that can run tasks independently without blocking the main flow of your application.</p><p>A small example:</p><pre>func printReceipt() {<br>    fmt.Println(&quot;Receipt printed&quot;)<br>}<br><br>func main() {<br>    go printReceipt()<br>    fmt.Println(&quot;Customer served&quot;)<br>}</pre><p>The go keyword tells Go:</p><blockquote><em>“Run this work separately so the main flow can continue.”</em></blockquote><p>Now back to our server.<br>The fix is to run ListenAndServe() in a goroutine so the main goroutine stays free to listen for operating system signals.</p><pre>func main() {<br>    mux := http.NewServeMux()<br>    mux.HandleFunc(&quot;/api/set&quot;, handler.Set)<br>    srv := &amp;http.Server{<br>        Addr: &quot;:8000&quot;,<br>        Handler: mux,<br>    }<br>    // Server runs independently<br>    go func() {<br>        log.Println(&quot;server starting on :8000&quot;)<br>        if err := srv.ListenAndServe(); err != nil &amp;&amp;<br>            err != http.ErrServerClosed {<br>            log.Fatalf(&quot;server error: %v&quot;, err)<br>        }<br>    }()<br>    // Main goroutine stays free<br>    quit := make(chan os.Signal, 1)<br>    signal.Notify(<br>        quit,<br>        syscall.SIGINT,<br>        syscall.SIGTERM,<br>    )<br>    &lt;-quit<br>    log.Println(&quot;signal received...&quot;)<br>}</pre><p>Going back to our restaurant story:</p><ul><li>one worker continues serving customers → ListenAndServe()</li><li>one worker stays near the manager waiting for instructions → main goroutine</li><li>emergency signal arrives → manager communicates with staff</li><li>restaurant begins safe shutdown procedures</li></ul><p>Why do we check:</p><pre>err != http.ErrServerClosed</pre><p>Later we will call:</p><pre>srv.Shutdown()</pre><p>When that happens, ListenAndServe() stops running and returns http.ErrServerClosed.</p><p>This is expected behavior.<br>Without this check, we would accidentally log a clean shutdown as if the server crashed.</p><p>Now our restaurant can both serve customers <strong>and</strong> stay aware of shutdown instructions — but we still have one missing piece.<br>Receiving the shutdown signal is not enough.</p><p>We still need to teach the restaurant how to close properly instead of shouting:</p><blockquote><em>“EVERYONE OUT. RIGHT NOW.”</em></blockquote><p>That’s what comes next.</p><h3>Step 3: Call srv.Shutdown() {#step-3-shutdown}</h3><p>Catching the signal alone is not enough.</p><p>Right now, our restaurant staff know that closing time has arrived, but nobody is actually telling the restaurant what to do next. Customers can still walk in. Orders can still arrive. That is not what we want.</p><p>When the manager gives the closing instruction, the restaurant should:</p><ul><li>stop accepting new customers</li><li>let customers already eating finish peacefully</li><li>clean up and close safely</li></ul><p>That is exactly what srv.Shutdown() does for our server.</p><pre>&lt;-quit<br>log.Println(&quot;shutting down...&quot;)<br>ctx, cancel := context.WithTimeout(<br>    context.Background(),<br>    30*time.Second,<br>)<br>defer cancel()<br>if err := srv.Shutdown(ctx); err != nil {<br>    log.Fatal(&quot;shutdown error:&quot;, err)<br>}<br>log.Println(&quot;server exited cleanly&quot;)</pre><p>Going back to our restaurant story: Manager gives the signal, Staff lock the front door. No new customers enter. Customers already inside finish eating. Kitchen wraps up remaining work. Restaurant closes properly.</p><p>Under the hood, srv.Shutdown() does two important things:</p><ol><li>Stops accepting new connections immediately</li><li>Waits for active requests to finish before returning</li></ol><p>This gives in-flight requests time to complete instead of being interrupted halfway.</p><p>You may also notice:</p><pre>context.WithTimeout(<br>    context.Background(),<br>    30*time.Second,<br>)</pre><p>The timeout acts as a safety boundary. Imagine one customer sits in the restaurant forever. We cannot keep the restaurant open endlessly.</p><p>If requests do not finish within 30 seconds, shutdown stops waiting and the process exits anyway.</p><p>This is already much better than abruptly shutting everything down.</p><p>But there is still a real problem.</p><p>A fixed timeout sounds simple, yet choosing the right number is harder than it looks.</p><h3>Step 4: The Fixed Timeout Tradeoff {#step-4-timeout-problem}</h3><p>Adding a timeout is better than abruptly shutting down the server, but choosing the timeout value introduces a tradeoff.</p><p>Consider these scenarios:</p><pre>no requests in flight  → exits immediately ✅<br>request takes 5s       → exits after ~5s ✅<br>request takes 45s      → timeout hits at 30s ❌</pre><p><strong>Going back to our restaurant example: </strong>management says:</p><blockquote><em>“Everyone must leave within 30 minutes.”</em></blockquote><p>Most days, that is perfectly fine.But what if a large group arrived right before closing? Force everyone out too early and work gets interrupted.<br>Wait too long and the restaurant stays open unnecessarily. Servers have the same challenge.</p><p>A timeout is not a precise answer it is a safety boundary.<br>Pick it too low and requests may get cut off.<br>Pick it too high and deployments or container shutdowns may take longer than necessary. The goal is not finding a magical timeout number. The goal is choosing a reasonable limit for your application’s workload.</p><p>The better question is: <strong>why guess at all?</strong> The server knows exactly when it is done. We should let it tell us.</p><h3>Step 5: WaitGroup: let the server tell you when it’s done {#step-5-waitgroup}</h3><p>At this point, we introduced a timeout to control shutdown. But there is still a deeper question:</p><blockquote><em>How do we know when all active requests are actually finished?</em></blockquote><p>This is where sync.WaitGroup helps. Think of it like a counter inside the restaurant:</p><ul><li>every active customer = +1</li><li>when they finish and leave = -1</li><li>when the counter reaches zero → the restaurant is truly empty</li></ul><pre>var wg sync.WaitGroup</pre><h3>In each request (handler):</h3><pre>wg.Add(1)<br>defer wg.Done()<br>// handler logic here</pre><p>Each incoming request registers itself when it starts, and removes itself when it finishes. On shutdown:</p><pre>go srv.Shutdown(context.Background()) // stop accepting new requests</pre><p>Now the server stops letting new customers in. But instead of guessing when everything is done, we wait for the actual signal:</p><pre>waitDone := make(chan struct{})<br>go func() {<br>    wg.Wait()       // waits until all requests are finished<br>    close(waitDone) // signals &quot;everything is done&quot;<br>}()</pre><p>Then we decide how long we are willing to wait as a safety net:</p><pre>select {<br>case &lt;-waitDone:<br>    log.Println(&quot;all requests finished, clean shutdown&quot;)<br>case &lt;-time.After(2 * time.Minute):<br>    log.Println(&quot;hard timeout reached, forcing exit&quot;)<br>}</pre><h3>What changed?</h3><p>Now the shutdown flow is no longer based on guessing time.<br>Instead:</p><ul><li>the server itself tells us when work is done</li><li>the timeout becomes only a fallback, not the main logic</li></ul><h3>In restaurant terms:</h3><ul><li>No more “everyone leave in 30 minutes no matter what”</li></ul><p>Instead:</p><ul><li>stop new customers</li><li>let current customers finish</li><li>leave when the restaurant is actually empty</li><li>only force close if something is stuck forever</li></ul><h3>Step 6: keep handlers clean with middleware {#step-6-middleware}</h3><p>Adding wg.Add(1) and wg.Done() to every handler is messy and easy to forget. If you miss one handler, your shutdown logic silently breaks.</p><p>The solution is a middleware that wraps every request automatically. Handlers stay completely unaware of shutdown logic:</p><pre>func trackRequests(wg *sync.WaitGroup, next http.Handler) http.Handler {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        wg.Add(1)<br>        defer wg.Done() // automatically called when handler returns<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>Apply it once at the top level:</p><pre>mid := trackRequests(&amp;wg,<br>    loggerMiddleware(<br>        metricsMiddleware(mux),<br>    ),<br>)<br>srv := &amp;http.Server{<br>    Addr:    &quot;:8000&quot;,<br>    Handler: mid,<br>}</pre><p>Every request that passes through mid is now tracked automatically. Your handlers only contain business logic no shutdown awareness, no WaitGroup references.</p><p>This is the core philosophy of HTTP middleware: <strong>cross-cutting concerns</strong> like logging, authentication, metrics, rate limiting, and shutdown tracking do not belong in handlers. Middleware intercepts the request lifecycle and handles them transparently.</p><h3>Step 7: second Ctrl+C as force kill with signal.NotifyContext {#step-7-force-kill}</h3><p>There is one more operator experience problem. If graceful shutdown is taking a long time say a slow request is still running the operator might hit Ctrl+C a second time meaning &quot;I don&#39;t care anymore, just die.&quot;</p><p>We should respect that.</p><p>signal.NotifyContext is the modern idiomatic way to handle signals in Go (introduced in Go 1.16). It wraps the signal in a context, which composes naturally with the rest of your code.</p><p>The key insight is what stop() does calling it releases the signal handler back to OS defaults. After that, the next Ctrl+C is no longer intercepted by your program. The OS handles it the default way: immediate termination.</p><pre>ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)<br>defer stop()<br>&lt;-ctx.Done() // blocks until first signal<br>log.Println(&quot;shutting down... (Ctrl+C again to force)&quot;)<br>// release the handler - second Ctrl+C now kills the process immediately via OS default<br>stop()</pre><p>No second channel needed. stop() is designed exactly for this pattern. After it is called, your program is no longer intercepting signals, so the operator has full control again.</p><h3>Step 8: make handlers respect shutdown via r.Context() {#step-8-handler-context}</h3><p>When srv.Shutdown() is called, Go cancels the context of every active request. Our handlers can listen for this and exit early instead of running to completion:</p><pre>func slowHandler(w http.ResponseWriter, r *http.Request) {<br>    select {<br>    case &lt;-time.After(2 * time.Minute): // normal work path<br>        w.Write([]byte(&quot;work done&quot;))<br>    case &lt;-r.Context().Done(): // shutdown cancelled this request<br>        log.Println(&quot;request interrupted by shutdown&quot;)<br>        http.Error(w, &quot;server shutting down&quot;, http.StatusServiceUnavailable)<br>        return<br>    }<br>}</pre><p>This matters for long-running handlers. Without it, a handler that sleeps for 2 minutes will keep the server alive for 2 minutes even after a shutdown signal, ignoring the shutdown context entirely. With it, the handler cooperates and exits early.</p><h3>Complete production-ready example {#complete-example}</h3><p>Here is everything put together signal handling, WaitGroup middleware, graceful shutdown with shared deadline, and second Ctrl+C force kill:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;os/signal&quot;<br>    &quot;sync&quot;<br>    &quot;syscall&quot;<br>    &quot;time&quot;<br>)<br>func main() {<br>    mux := http.NewServeMux()<br>    mux.HandleFunc(&quot;/api/get&quot;, handler.Get)<br>    mux.HandleFunc(&quot;/api/set&quot;, handler.Set)<br>    mux.HandleFunc(&quot;/health&quot;, handler.Health)<br>    var wg sync.WaitGroup<br>    // keep under Kubernetes terminationGracePeriodSeconds (default 30s)<br>    const shutdownTimeout = 25 * time.Second<br>    mid := trackRequests(&amp;wg,<br>        loggerMiddleware(<br>            metricsMiddleware(mux),<br>        ),<br>    )<br>    srv := &amp;http.Server{<br>        Addr:    &quot;:8000&quot;,<br>        Handler: mid,<br>    }<br>    // start server in goroutine so main is not blocked<br>    go func() {<br>        log.Println(&quot;server starting on :8000&quot;)<br>        if err := srv.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {<br>            log.Fatalf(&quot;server error: %v&quot;, err)<br>        }<br>    }()<br>    // wait for SIGINT or SIGTERM<br>    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)<br>    defer stop()<br>    &lt;-ctx.Done()<br>    log.Println(&quot;shutting down... (Ctrl+C again to force)&quot;)<br>    // release signal handler - second Ctrl+C now kills via OS default<br>    stop()<br>    // shared deadline for both Shutdown and WaitGroup<br>    shutCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)<br>    defer cancel()<br>    // stop accepting new requests, respects the deadline<br>    go srv.Shutdown(shutCtx)<br>    // wait for in-flight requests to finish<br>    waitDone := make(chan struct{})<br>    go func() {<br>        wg.Wait()<br>        close(waitDone)<br>    }()<br>    select {<br>    case &lt;-waitDone:<br>        log.Println(&quot;all requests done, clean exit&quot;)<br>    case &lt;-shutCtx.Done():<br>        log.Printf(&quot;shutdown timeout after %s, forcing exit\n&quot;, shutdownTimeout)<br>    }<br>}<br>// trackRequests is middleware that tracks in-flight requests via WaitGroup.<br>// Handlers remain completely unaware of shutdown logic.<br>func trackRequests(wg *sync.WaitGroup, next http.Handler) http.Handler {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        wg.Add(1)<br>        defer wg.Done()<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><h3>Kubernetes and terminationGracePeriodSeconds {#kubernetes}</h3><p>If you deploy to Kubernetes, this is especially important. When a pod is stopped, Kubernetes sends SIGTERM and then waits terminationGracePeriodSeconds (default: 30 seconds) before sending SIGKILL.</p><p>SIGKILL cannot be caught or handled the OS kills the process immediately regardless of what your code is doing.</p><p>The rule of thumb: <strong>set your shutdown timeout slightly under </strong><strong>terminationGracePeriodSeconds</strong>:</p><pre>// k8s gives 30s before SIGKILL — use 25s so we exit cleanly before that<br>const shutdownTimeout = 25 * time.Second</pre><p>If you need more time for long-running requests, increase terminationGracePeriodSeconds in your pod spec:</p><pre>spec:<br>  terminationGracePeriodSeconds: 60  # give 60s before SIGKILL</pre><p>And match your shutdown timeout:</p><pre>const shutdownTimeout = 55 * time.Second</pre><h3>Summary: why each piece exists {#summary}</h3><p>Piece Why it exists Goroutine for ListenAndServe ListenAndServe blocks main needs to stay free to handle signals and run shutdown logic signal.NotifyContext intercepts SIGINT/SIGTERM before the OS kills the process modern replacement for signal.Notify stop() after first signal releases the signal handler so a second Ctrl+C kills the process immediately via OS default srv.Shutdown() stops new connections, waits for active ones the core of graceful shutdown sync.WaitGroup + middleware server tells you when it is done rather than guessing with a fixed timeout Shared shutCtx deadline single source of truth for both Shutdown and the selectno drift between two separate timers r.Context().Done() in handlers long-running handlers cooperate with shutdown instead of ignoring it http.ErrServerClosed check distinguishes an intentional shutdown from a real server crash</p><h3>Common mistakes to avoid</h3><p><strong>Using </strong><strong>context.Background() in </strong><strong>srv.Shutdown</strong> this has no deadline, so if a request is stuck, Shutdown waits forever. Always pass a context with a timeout.</p><p><strong>Two separate timers</strong> using both context.WithTimeout for Shutdown and a separate time.After in select creates two independent countdowns that drift apart. Use one shared shutCtx for both.</p><p><strong>Calling </strong><strong>log.Fatal after server start</strong>log.Fatal calls os.Exit(1), which skips all deferred functions and shutdown logic. Only use it for unrecoverable startup errors inside the goroutine.</p><p><strong>Not checking </strong><strong>http.ErrServerClosed</strong> without this check, a clean shutdown logs as a fatal crash.</p><p><strong>Missing </strong><strong>trackRequests middleware</strong> if wg is never incremented, wg.Wait() returns immediately, waitDone closes instantly, and the WaitGroup approach does nothing. The middleware is not optional.</p><p><em>Built from real debugging sessions not just theory. Every mistake in this article was made and fixed in a working Go server.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=555329cda4fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving a Mystery Using SQL: A Detective’s Journey Through Databases and Clues]]></title>
            <link>https://wajedkhan.medium.com/solving-a-mystery-using-sql-a-detectives-journey-through-databases-and-clues-e9daf70c2bc1?source=rss-a27e5195dae8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9daf70c2bc1</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[funlearning]]></category>
            <dc:creator><![CDATA[Wazed Khan]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 16:36:45 GMT</pubDate>
            <atom:updated>2026-10-08T11:28:15.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Murder Mystery Walkthrough: Solve a Crime with SQL</h3><h3>One murder, two culprits, and every core SQL skill you need to catch them</h3><p>There has been a murder in SQL City. The detective handed you the crime scene report, and you lost it 😶. All you remember is three things: it was a <strong>murder</strong>, it happened on <strong>January 15, 2018</strong>, and it took place in <strong>SQL City</strong>.</p><p>Asking the police for another copy would be embarrassing. Luckily, we know SQL. In this <strong>SQL murder mystery walkthrough</strong> we solve the whole case with nothing but queries, one clue at a time, and keep a Detective Diary so you can see how each clue leads to the next. Along the way you will use SELECT, LIKE, IN, JOIN, BETWEEN, GROUP BY and HAVING.</p><blockquote><strong><em>Spoiler warning:</em></strong><em> this article contains the full solution. The puzzle is the </em><a href="https://mystery.knightlab.com/"><em>SQL Murder Mystery</em></a><em> by Knight Lab, created by Joon Park and Cathy He. If you want to crack it yourself, try it there first and come back when you are done or stuck.</em></blockquote><h3>Step 1: Know your database, then find the report</h3><p>A good detective studies the scene before touching anything. For us, the scene is the schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*FixmMKxS8yTBe9ZW.png" /></figure><p><em>The police department’s database schema (Knight Lab, CC BY-SA 4.0)</em></p><p>The database is SQLite. If you ever land in an unknown SQLite database, this lists every table:</p><pre>SELECT name FROM sqlite_master WHERE type = &#39;table&#39;;</pre><p>The table we need first is crime_scene_report. We know the type, the date and the city, so we filter on all three. Dates are stored as numbers in YYYYMMDD form, so January 15, 2018 becomes 20180115.</p><pre>SELECT *<br>FROM crime_scene_report<br>WHERE type = &#39;murder&#39;<br>  AND date = 20180115<br>  AND city = &#39;SQL City&#39;;</pre><pre>date        : 20180115<br>type        : murder<br>description : Security footage shows that there were 2 witnesses. The<br>              first witness lives at the last house on &quot;Northwestern Dr&quot;.<br>              The second witness, named Annabel, lives somewhere on<br>              &quot;Franklin Ave&quot;.<br>city        : SQL City</pre><p><em>SQL used: SELECT, FROM, WHERE, AND</em></p><p>No weapon, no suspect, just two witnesses. Time to open the diary.</p><pre>Detective Diary<br>---------------<br>(1) Crime scene report<br>    - Witness 1: lives in the LAST house on Northwestern Dr<br>    - Witness 2: named Annabel, lives somewhere on Franklin Ave</pre><h3>Step 2: Find the witnesses</h3><p>The person table has names and addresses, so that is where our witnesses live (literally).</p><p><strong>Witness 1</strong> lives in the <em>last</em> house on Northwestern Dr. “Last” means the highest house number, so we sort descending and take the top row.</p><pre>SELECT *<br>FROM person<br>WHERE address_street_name = &#39;Northwestern Dr&#39;<br>ORDER BY address_number DESC<br>LIMIT 1;</pre><pre>+-------+----------------+------------+----------------+---------------------+-----------+<br>| id    | name           | license_id | address_number | address_street_name | ssn       |<br>+-------+----------------+------------+----------------+---------------------+-----------+<br>| 14887 | Morty Schapiro | 118009     | 4919           | Northwestern Dr     | 111564949 |<br>+-------+----------------+------------+----------------+---------------------+-----------+</pre><p><strong>Witness 2</strong> is Annabel on Franklin Ave. We only have one name, and it could be a first or last name, so we put % on both sides. LIKE &#39;%Annabel%&#39; matches &quot;Annabel&quot; anywhere in the name.</p><pre>SELECT *<br>FROM person<br>WHERE name LIKE &#39;%Annabel%&#39;<br>  AND address_street_name = &#39;Franklin Ave&#39;;</pre><pre>+-------+----------------+------------+----------------+---------------------+-----------+<br>| id    | name           | license_id | address_number | address_street_name | ssn       |<br>+-------+----------------+------------+----------------+---------------------+-----------+<br>| 16371 | Annabel Miller | 490173     | 103            | Franklin Ave        | 318771143 |<br>+-------+----------------+------------+----------------+---------------------+-----------+</pre><p><em>SQL used: ORDER BY, DESC, LIMIT, LIKE with %</em></p><h3>Step 3: Read what the witnesses told the police</h3><p>The interview table links to people through person_id. We have both IDs now, so one query gets both statements.</p><pre>SELECT *<br>FROM interview<br>WHERE person_id IN (14887, 16371);</pre><pre>person_id   : 14887<br>transcript  : I heard a gunshot and then saw a man run out. He had a &quot;Get<br>              Fit Now Gym&quot; bag. The membership number on the bag started<br>              with &quot;48Z&quot;. Only gold members have those bags. The man got<br>              into a car with a plate that included &quot;H42W&quot;.<br>--------------------<br>person_id   : 16371<br>transcript  : I saw the murder happen, and I recognized the killer from my<br>              gym when I was working out last week on January the 9th.</pre><p><em>SQL used: IN</em></p><p>Now we are getting somewhere. That is five separate clues about one man.</p><pre>Detective Diary<br>---------------<br>(2) Witness statements: the killer is...<br>    - a man<br>    - a Get Fit Now Gym member, GOLD status<br>    - membership number starts with &quot;48Z&quot;<br>    - car plate contains &quot;H42W&quot; (could be anywhere in the plate)<br>    - was at the gym on January 9, 2018</pre><h3>Step 4: Follow the car</h3><p>The drivers_license table has plate numbers and gender. The plate <em>includes</em> &quot;H42W&quot;, but we don&#39;t know where, so % goes on both sides again.</p><pre>SELECT *<br>FROM drivers_license<br>WHERE plate_number LIKE &#39;%H42W%&#39;<br>  AND gender = &#39;male&#39;;</pre><pre>+--------+-----+--------+-----------+------------+--------+--------------+-----------+-----------+<br>| id     | age | height | eye_color | hair_color | gender | plate_number | car_make  | car_model |<br>+--------+-----+--------+-----------+------------+--------+--------------+-----------+-----------+<br>| 423327 | 30  | 70     | brown     | brown      | male   | 0H42W2       | Chevrolet | Spark LS  |<br>| 664760 | 21  | 71     | black     | black      | male   | 4H42WR       | Nissan    | Altima    |<br>+--------+-----+--------+-----------+------------+--------+--------------+-----------+-----------+</pre><p>Two licenses. Who owns them?</p><pre>SELECT *<br>FROM person<br>WHERE license_id IN (423327, 664760);</pre><pre>+-------+----------------+------------+----------------+-----------------------+-----------+<br>| id    | name           | license_id | address_number | address_street_name   | ssn       |<br>+-------+----------------+------------+----------------+-----------------------+-----------+<br>| 51739 | Tushar Chandra | 664760     | 312            | Phi St                | 137882671 |<br>| 67318 | Jeremy Bowers  | 423327     | 530            | Washington Pl, Apt 3A | 871539279 |<br>+-------+----------------+------------+----------------+-----------------------+-----------+</pre><p>Two suspects. One would have been nicer, but we still have the gym clues. 😎</p><h3>Step 5: Check the gym</h3><p>Annabel saw the killer at the gym on January 9. The get_fit_now_check_in table records every visit. This time the % goes only at the end, because the membership number <em>starts with</em> 48Z.</p><pre>SELECT *<br>FROM get_fit_now_check_in<br>WHERE check_in_date = 20180109<br>  AND membership_id LIKE &#39;48Z%&#39;;</pre><pre>+---------------+---------------+---------------+----------------+<br>| membership_id | check_in_date | check_in_time | check_out_time |<br>+---------------+---------------+---------------+----------------+<br>| 48Z7A         | 20180109      | 1600          | 1730           |<br>| 48Z55         | 20180109      | 1530          | 1700           |<br>+---------------+---------------+---------------+----------------+</pre><p>Two members checked in that day. Let’s see who they are, using the exact IDs we just found plus the “gold only” clue.</p><pre>SELECT *<br>FROM get_fit_now_member<br>WHERE id IN (&#39;48Z7A&#39;, &#39;48Z55&#39;)<br>  AND membership_status = &#39;gold&#39;;</pre><pre>+-------+-----------+---------------+-----------------------+-------------------+<br>| id    | person_id | name          | membership_start_date | membership_status |<br>+-------+-----------+---------------+-----------------------+-------------------+<br>| 48Z55 | 67318     | Jeremy Bowers | 20160101              | gold              |<br>| 48Z7A | 28819     | Joe Germuska  | 20160305              | gold              |<br>+-------+-----------+---------------+-----------------------+-------------------+</pre><p>Still two names. But look at person_id. Our car suspects were 51739 and 67318, and only <strong>Jeremy Bowers (67318)</strong> appears in both lists: right car, right gym, right day.</p><p>We can prove it in one query by joining all the clues together:</p><pre>SELECT p.id, p.name, m.id AS membership_id, d.plate_number<br>FROM person p<br>JOIN drivers_license d ON p.license_id = d.id<br>JOIN get_fit_now_member m ON m.person_id = p.id<br>JOIN get_fit_now_check_in c ON c.membership_id = m.id<br>WHERE d.plate_number LIKE &#39;%H42W%&#39;<br>  AND m.membership_status = &#39;gold&#39;<br>  AND m.id LIKE &#39;48Z%&#39;<br>  AND c.check_in_date = 20180109;</pre><pre>+-------+---------------+---------------+--------------+<br>| id    | name          | membership_id | plate_number |<br>+-------+---------------+---------------+--------------+<br>| 67318 | Jeremy Bowers | 48Z55         | 0H42W2       |<br>+-------+---------------+---------------+--------------+</pre><p><em>SQL used: JOIN across four tables</em></p><p><strong>Voilà.</strong> We have our killer. 🎉</p><h3>Step 6: Why did he do it?</h3><p>A good detective never stops at <em>who</em>. Let’s read Jeremy’s own interview.</p><pre>SELECT *<br>FROM interview<br>WHERE person_id = 67318;</pre><pre>person_id   : 67318<br>transcript  : I was hired by a woman with a lot of money. I don&#39;t know her<br>              name but I know she&#39;s around 5&#39;5&quot; (65&quot;) or 5&#39;7&quot; (67&quot;). She<br>              has red hair and she drives a Tesla Model S. I know that she<br>              attended the SQL Symphony Concert 3 times in December 2017.</pre><p>Plot twist. Jeremy was only the hitman. Someone hired him.</p><pre>Detective Diary<br>---------------<br>(3) The killer: Jeremy Bowers (person 67318, member 48Z55)<br>(4) The person who hired him is a woman who...<br>    - has a lot of money<br>    - is 65&quot; to 67&quot; tall<br>    - has red hair<br>    - drives a Tesla Model S<br>    - attended the SQL Symphony Concert 3 times in December 2017</pre><h3>Step 7: Find the woman in the Tesla</h3><p>The drivers_license table covers almost everything Jeremy described. BETWEEN handles the height range and includes both ends.</p><pre>SELECT *<br>FROM drivers_license<br>WHERE gender = &#39;female&#39;<br>  AND hair_color = &#39;red&#39;<br>  AND car_make = &#39;Tesla&#39;<br>  AND car_model = &#39;Model S&#39;<br>  AND height BETWEEN 65 AND 67;</pre><pre>+--------+-----+--------+-----------+------------+--------+--------------+----------+-----------+<br>| id     | age | height | eye_color | hair_color | gender | plate_number | car_make | car_model |<br>+--------+-----+--------+-----------+------------+--------+--------------+----------+-----------+<br>| 202298 | 68  | 66     | green     | red        | female | 500123       | Tesla    | Model S   |<br>| 291182 | 65  | 66     | blue      | red        | female | 08CM64       | Tesla    | Model S   |<br>| 918773 | 48  | 65     | black     | red        | female | 917UU3       | Tesla    | Model S   |<br>+--------+-----+--------+-----------+------------+--------+--------------+----------+-----------+</pre><p>Three red-haired women in Tesla Model S cars. Two clues left: money and music.</p><h3>Step 8: Follow the money</h3><p>Jeremy said she has a lot of money. The income table is keyed by SSN, so we join through person.</p><pre>SELECT p.name, i.annual_income<br>FROM drivers_license d<br>JOIN person p ON p.license_id = d.id<br>JOIN income i ON i.ssn = p.ssn<br>WHERE d.id IN (202298, 291182, 918773)<br>ORDER BY i.annual_income DESC;</pre><pre>+------------------+---------------+<br>| name             | annual_income |<br>+------------------+---------------+<br>| Miranda Priestly | 310000        |<br>| Red Korb         | 278000        |<br>+------------------+---------------+</pre><p>Both are wealthy, and the third suspect has no income record at all. Money narrows it down, but it doesn’t settle it. The concert will.</p><h3>Step 9: The SQL Symphony Concert</h3><p>She went to the concert <strong>three times</strong> in December 2017. Instead of counting rows by eye, let SQL count with GROUP BY and HAVING.</p><pre>SELECT p.id, p.name, COUNT(*) AS visits<br>FROM person p<br>JOIN facebook_event_checkin f ON f.person_id = p.id<br>WHERE f.event_name = &#39;SQL Symphony Concert&#39;<br>  AND f.date LIKE &#39;201712%&#39;<br>  AND p.license_id IN (202298, 291182, 918773)<br>GROUP BY p.id, p.name<br>HAVING COUNT(*) = 3;</pre><pre>+-------+------------------+--------+<br>| id    | name             | visits |<br>+-------+------------------+--------+<br>| 99716 | Miranda Priestly | 3      |<br>+-------+------------------+--------+</pre><p>WHERE filters rows <em>before</em> grouping. HAVING filters groups <em>after</em> counting. That difference is one of the most useful ideas in SQL, and it just caught our mastermind.</p><p><em>SQL used: GROUP BY, COUNT, HAVING</em></p><h3>Case closed: check your answer</h3><p>The original game lets you submit an answer and tells you whether you are right. On the <a href="https://mystery.knightlab.com/">mystery site</a>, run:</p><pre>INSERT INTO solutions VALUES (1, &#39;Miranda Priestly&#39;);<br>SELECT value FROM solutions;</pre><p>The site confirms it. Jeremy Bowers pulled the trigger, and <strong>Miranda Priestly</strong> paid for it.</p><pre>Detective Diary<br>---------------<br>(5) CASE CLOSED<br>    - Killer:     Jeremy Bowers<br>    - Mastermind: Miranda Priestly (3 concert visits, $310,000 income)</pre><h3>What we learned</h3><p>One murder, two culprits, and almost every core SQL skill along the way:</p><pre>Clue                          SQL that cracked it<br>----------------------------  ------------------------------<br>Lost crime report             SELECT, WHERE, AND<br>&quot;Last house on the street&quot;    ORDER BY ... DESC LIMIT 1<br>Partial names and plates      LIKE with %<br>Two witnesses at once         IN<br>Car + gym + check-in          JOIN across four tables<br>Height range                  BETWEEN<br>&quot;Three times&quot;                 GROUP BY, COUNT, HAVING</pre><p>Now go solve one yourself. Knight Lab has the full game at <a href="https://mystery.knightlab.com/">mystery.knightlab.com</a>. If this helped you, a clap 👏 or a share helps other learners find it.</p><p><strong>Credits.</strong> The SQL Murder Mystery was created by Joon Park and Cathy He as Knight Lab fellows and adapted for the web by Joe Germuska (<a href="https://github.com/NUKnightLab/sql-mysteries">GitHub</a>). Its original text, data and schema image are licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>. This walkthrough is an adaptation and is shared under the same license.</p><p><em>Written by </em><a href="https://wazedkhan.github.io/"><em>Wazed Khan</em></a><em>, backend engineer. Find me on </em><a href="https://www.linkedin.com/in/wajed-khan"><em>LinkedIn</em></a><em> and </em><a href="https://github.com/WazedKhan"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9daf70c2bc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sub-classing Python’s / Extending Built-in Immutable Classes in Python]]></title>
            <link>https://wajedkhan.medium.com/sub-classing-pythons-extending-built-in-immutable-classes-in-python-a06c9ecb759d?source=rss-a27e5195dae8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06c9ecb759d</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Wazed Khan]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 02:36:00 GMT</pubDate>
            <atom:updated>2024-07-01T02:36:00.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever needed to extend the functionality of Python’s built-in immutable classes like `float`, `int`, or `str`? Whether you want to add additional features or create a similar custom class with more functionalities, Python allows you to do just that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKDhMT_Gypq1WsupZi8nKA.png" /></figure><h3>What we will discuss in this article:</h3><ul><li><strong>Introduction to Sub-classing Built-in Types: </strong>A brief overview of why and when you might want to subclass built-in immutable types like float.</li><li><strong>Scenario Explanation:</strong> Discuss a specific scenario where we need to work with distances in our application and want to leverage the existing functionality of the float type while also maintaining the unit of measurement.</li><li><strong>Basic Implementation Attempt:</strong> Show a naive implementation attempt of sub-classing float and explain why it fails due to the immutable nature of built-in types.</li><li><strong>Understanding the TypeError:</strong> Provide a detailed explanation of why the TypeError occurs when trying to subclass and initialize an immutable type like float.</li><li><strong>Correcting the Approach with </strong><strong>__new__ :</strong> Introduce the __new__ method, explaining its role in creating instances of immutable types and how it differs from __init__.</li><li><strong>Example Implementation Using </strong><strong>__new__ :</strong> Provide a corrected implementation of the Distance class using the __new__ method to properly subclass float and add additional attributes.</li><li><strong>Explanation of Corrected Code: </strong>Break down the corrected implementation step-by-step, highlighting key points and demonstrating how the class can be used in practice.</li></ul><h3>What is sub-classing:</h3><p>If you are familiar with OOP, you probably already understand subclassing. To refresh the concept, subclasses are classes that inherit from a parent class. This means that each child class can utilize the methods and variables of the parent class.</p><h3>Scenario Explanation</h3><p>Given the scenario where we need to work with distances in our application and want to leverage the existing functionality of the `float` type while also maintaining the unit of measurement, sub-classing `float` is a good solution. This approach allows us to extend `float` to include the unit and provide additional functionality specific to distances.</p><h3>let us try out the basic implementation by ignoring that float is an immutable class</h3><pre>1 class Distance(float):<br>2     def __init__(self, value, unit):<br>3        super().__init__(value)<br>4        self.unit = unit<br><br>output:<br>---------------------------------------------------<br>in_miles = Distance(42.0, &quot;Miles&quot;)<br>output:<br>TypeError: float expected at most 1 argument, got 2py</pre><h4>Understanding the TypeError</h4><p>so when we subclass a built-in immutable type like float, Python expects us to initialize the instance during its creation using the `__new__` method. Here’s why:</p><blockquote><strong>NOTE:</strong> In Python, immutable types such as float, int, and tuple do not allow their instances to be modified after they are created. This immutability is enforced to ensure the consistency and integrity of these fundamental types.</blockquote><h4>Error Cause:</h4><ul><li>In our code, we tried to use `super().__ init __(value)` in the `__ init __` method of Distance. However, the float does not accept multiple arguments in its constructor because it expects only one argument (the numerical value).</li><li>This mismatch between the number of arguments (value and unit) and what float expects led to the TypeError.</li></ul><h4>Immutable Nature:</h4><ul><li>Immutable types cannot have their state changed after creation. This means attributes cannot be added or modified after the instance is instantiated.</li><li>Since float objects are immutable, their value cannot be changed once they are created. Therefore, the `__ init __` method, which is called after the instance is created, cannot be used to modify the object’s state.</li></ul><h4>__new__ vs __init__:</h4><ol><li><strong>__new__()</strong>: Responsible for creating a new instance of the class. It’s called first and returns a new object instance.</li><li><strong>__init __():</strong> Initializes the created instance after it has been created by `__ new __`. It’s used to set up initial attributes and state.</li></ol><h3>#Correct Approach</h3><p>To correctly subclass `float` and include additional attributes like `unit`, we should override the `__new__` method to initialize the instance with both the value and the unit. Here’s the corrected approach:</p><pre>class Distance(float):<br>    def __new__(cls, value, unit):<br>        instance = super().__new__(cls, value)<br>        instance.unit = unit<br>        return instance<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    in_miles = Distance(42.0, &quot;Miles&quot;)<br>    print(in_miles)  # Output: 42.0<br>    print(in_miles.unit)  # Output: Miles</pre><h3>Explanation of the Corrected Code</h3><ul><li>__new__ Method :</li><li>super().__new__(cls, value) calls the __new__ method of the superclass (float in this case) to create a new instance with the given value.</li><li>The unit attribute is then added to the instance (instance.unit = unit).</li><li>Finally, the modified instance is returned (return instance).</li><li>Example Usage :</li><li>Distance(42.0, &quot;Miles&quot;) creates a new Distance object with a value of 42.0 and unit &quot;Miles&quot;.</li><li>Printing in_miles shows 42.0, indicating that the object behaves like a float.</li><li>Accessing in_miles.unit retrieves the unit &quot;Miles&quot;, demonstrating that the additional attribute unit is correctly stored and accessible.</li></ul><p>By using __new__ instead of __init__, you align with Python&#39;s conventions for creating instances of immutable types and avoid the TypeError caused by attempting to pass multiple arguments to the float constructor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06c9ecb759d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Objects with Precision Python]]></title>
            <link>https://wajedkhan.medium.com/pythons-new-method-crafting-objects-with-precision-862f29af31c8?source=rss-a27e5195dae8------2</link>
            <guid isPermaLink="false">https://medium.com/p/862f29af31c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[oop-python]]></category>
            <dc:creator><![CDATA[Wazed Khan]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 03:04:45 GMT</pubDate>
            <atom:updated>2024-06-20T03:43:56.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKDhMT_Gypq1WsupZi8nKA.png" /></figure><h3>Purpose of __ new __</h3><p>The primary role of __new__ is to create and return a new instance of a class. It is called before __init__, which initializes the created instance. Here’s a step-by-step breakdown:</p><ol><li><strong>Class Creation: </strong>When we write a class and create an instance of it, Python internally calls __new__ to create the object.</li><li><strong>Instance Initialization:</strong> After __new__ creates the instance, Python then calls __init__ to initialize it.</li></ol><h3>Basic Usage:</h3><pre>class MyClass:<br>    def __new__(cls, *args, **kwargs):<br>        # Custom object creation logic goes here<br>        instance = super().__new__(cls)<br>        # Additional initialization can be done here if needed<br>        return instance<br>    <br>    def __init__(self, *args, **kwargs):<br>        # Instance initialization code goes here<br>        pass<br><br># Creating an instance of MyClass<br>obj = MyClass()</pre><h3>Explanation:</h3><blockquote><strong><em>__new__ Method:</em></strong></blockquote><ol><li><strong>Parameters:</strong> __new__ accepts the class (cls) as the first parameter, followed by any additional arguments (*args) and keyword arguments (**kwargs).</li><li><strong>Customization:</strong> we can override __new__ to customize how instances of our class are created. This could involve creating the instance using a different method or adding additional attributes.</li><li><strong>Return Value:</strong> __new__ should return an instance of the class (cls). Typically, we create the instance using super().__new__(cls) to invoke the parent class&#39;s __new__ method.</li></ol><blockquote><strong><em>__ init __ Method:</em></strong></blockquote><ol><li><strong>Initialization:</strong> __init__ initializes the instance after it has been created by __new__. It&#39;s where we typically set up initial attributes and perform any other initialization tasks.</li></ol><h3>Example:</h3><p>Let’s say we have a class Person where we want to ensure that every person’s name is capitalized when the instance is created:</p><pre>class Person:<br>    def __new__(cls, name):<br>        # Ensure name is capitalized<br>        capitalized_name = name.capitalize()<br>        instance = super().__new__(cls)<br>        instance.name = capitalized_name<br>        return instance<br>    <br>    def __init__(self, name):<br>        # Initialization can be done here, if needed<br>        pass</pre><pre># Creating instances<br>person1 = Person(&quot;Wajed&quot;)<br>person2 = Person(&quot;Tintin&quot;)</pre><pre>print(person1.name)  # Output: Wajed<br>print(person2.name)  # Output: Tintin</pre><h3>Conclusion:</h3><ul><li><strong>Control over Instance Creation:</strong> __new__ provides control over how instances are created. This is useful for customizing object creation logic or enforcing constraints.</li><li><strong>Static/Class Method:</strong> Even though it’s commonly referred to as static due to its usage pattern, technically it’s a class method because Python passes the class (cls) implicitly.</li><li><strong>Usage: </strong>While __init__ is where we typically initialize instance attributes, __new__ allows for more advanced customization of instance creation, making it powerful for handling special cases or enforcing specific behaviors during object instantiation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862f29af31c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>