<?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 Jayant Nehra on Medium]]></title>
        <description><![CDATA[Stories by Jayant Nehra on Medium]]></description>
        <link>https://medium.com/@jayantnehra18?source=rss-4dfcfb6b38a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pZzpOCJaQfYL8KN46o-NkQ.jpeg</url>
            <title>Stories by Jayant Nehra on Medium</title>
            <link>https://medium.com/@jayantnehra18?source=rss-4dfcfb6b38a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:05:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayantnehra18/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[LLM Reasoning effort is not a monotone quality dial]]></title>
            <link>https://medium.com/@jayantnehra18/llm-reasoning-effort-is-not-a-monotone-quality-dial-be87bd9290d0?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be87bd9290d0</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 17:05:45 GMT</pubDate>
            <atom:updated>2026-08-21T17:05:45.927Z</atom:updated>
            <content:encoded><![CDATA[<p>Reasoning models expose a compute parameter: reasoning_effort on OpenAI models, budget_tokens on Anthropic&#39;s thinking blocks. You pay for tokens the model generates and discards in exchange for a better final answer.</p><p>I had been treating it as monotone. Harder task, higher setting, better output, higher bill.</p><p>On a skill-driven agent workflow, a large instruction set plus reference documents, assets and callable scripts, raising it helped. Then I raised it again and output quality fell. Not by erroring. The model would reach a correct decision, continue, revisit that decision later in the same trace, and reverse it. Work that was right at the lower setting was wrong at the higher one.</p><p>I have not measured the curve. What follows is the mechanism I think produces it, and the experiment that would confirm or kill it.</p><h3>The wrong assumption</h3><p>My first read was instability at high effort, with the fix being to find a ceiling and stay under it.</p><p>Underneath that was an assumption I had not examined: that low-effort failures and high-effort failures are the same failure, and reasoning is strictly more of the cure. They are not the same failure. They move in opposite directions, and the ceiling is where they cross.</p><h3>The revision balance</h3><p>A reasoning trace that revisits its own work is running an edit pass, and an edit pass is two-sided. It converts wrong items to right, and right items to wrong.</p><p>Let a be accuracy before the pass, p_fix the probability it corrects a given wrong item, p_break the probability it corrupts a given correct item. Expected change in accuracy:</p><pre>Δ = (1 - a)·p_fix - a·p_break</pre><p>Positive while a &lt; p_fix / (p_fix + p_break), negative after.</p><p>Two things follow, and both are testable.</p><p>The peak is not a property of the model or the setting. It is a property of accuracy going into the pass. Two tasks on identical settings turn at different points if one starts closer to correct.</p><p>And there is a ceiling that additional effort cannot cross, sitting at p_fix / (p_fix + p_break). Once accuracy reaches it the process is at a fixed point: revisions fix and break at equal rates. Every increment of effort past that is paid for a random walk.</p><p>That is the general form. It says nothing yet about why the turn arrives early on this particular workload.</p><h3>Instruction conflicts</h3><p>Any substantial instruction set contains constraints that are not jointly satisfiable at the margin. Be thorough, be concise. Follow the reference, use judgement where it does not cover the case. Prefer the existing convention, fix what is clearly wrong.</p><p>These are not contradictions. They are a partial order with no total order over it, so there are multiple Pareto-equivalent resolutions and no fact of the matter distinguishing them.</p><p>A short trace picks one, usually the resolution the most salient instruction supports, and commits. A long trace has room to reopen it. Reopening a choice between Pareto-equivalent resolutions is not convergence, because there is nothing to converge on. It is a random walk over the resolution set, and each step is locally justifiable by some constraint in the payload.</p><p>This raises p_break without raising p_fix, which by the expression above moves the peak left. The more instructions, the more conflicting pairs, the further left it moves.</p><p>The failure I watched was not the model losing the plot. Each individual step of its reasoning was defensible against something in the instructions.</p><h3>Trace share of context</h3><p>A weaker mechanism, and I cannot currently separate it from the previous one.</p><p>Reasoning tokens occupy the same context window as the input and accumulate monotonically through the trace. Late in a long trace, a substantial share of what the model conditions on is text it generated itself, positioned more recently than the reference material and more locally coherent with the next token.</p><p>If that share is what drives the drift, the fix is trace management rather than instruction design, and the two have opposite remedies. Both produce the same external symptom, which is why I am not asserting either.</p><h3>What would settle it</h3><p>The measurement is a sweep.</p><p>Thirty to a hundred cases from the real workload with a scoreable outcome. Four or five settings across the range. Hold prompt, payload, model and temperature fixed. Log per run, not per sweep:</p><pre>case_id, setting, score, input_tokens, reasoning_tokens, output_tokens</pre><p>Reasoning tokens bill separately from output tokens. Logging them together makes the cost curve wrong in the direction that flatters high settings.</p><p>The interesting point is where accuracy flattens, not where it declines. Flattening is the ceiling term. By the time decline is visible on thirty cases the setting is well past useful.</p><p>Then the part that discriminates between the two mechanisms: rerun the sweep against a trimmed instruction payload, same cases, same settings. If the peak moves right, the payload is driving it and the instruction-conflict account holds. If the peak does not move, that account is wrong and the trace-share account survives.</p><h3>Open</h3><p>I have not established which mechanism dominates, and the setup I have may not be able to separate them.</p><p>What I did rule out is the simplest alternative, that the model was losing the instructions at high effort. It was not. Asked directly at the high setting, it reproduced them accurately. It had reasoned past them, not forgotten them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be87bd9290d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request to Response]]></title>
            <link>https://medium.com/@jayantnehra18/request-to-response-3ce22367157a?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce22367157a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 11:09:14 GMT</pubDate>
            <atom:updated>2025-08-03T11:09:14.381Z</atom:updated>
            <content:encoded><![CDATA[<p>The Illusion of Simplicity</p><p>Most of us start building APIs because we need to expose something — a model, a service, a piece of data — to the outside world.</p><p>Frameworks like FastAPI makes that feel effortless. We define a function, add a decorator, run a single command, and suddenly our code is reachable by anyone who knows the URL.</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br>@app.post(&quot;/predict&quot;)<br>def predict(input: dict):<br>    return {&quot;result&quot;: &quot;some_prediction&quot;}</pre><p>It works. We know the routine now: create the app, define an endpoint, run uvicorn main:app --reload, and everything just… works.</p><p>But at some point, a question creeps in: <strong>what are we actually doing here?</strong></p><p>A request goes out, our function runs, and a response comes back. But what does it mean for a request to “arrive”? What makes our function an “endpoint”? What makes FastAPI an “application,” and Uvicorn a “server”?</p><p>This series is result of my curiosity while jumping into this domain of API Engineering. Not by memorizing more patterns, but by unpacking what happens from the moment a request leaves a client’s machine to the moment it reaches our FastAPI function — and how it finds its way back again.</p><p>I am doing it because understanding the fundamentals is how we move beyond following recipes. It’s how we avoid “20 years of one-year experience,” where we repeat steps without ever really grasping them.</p><p>So let’s start with the big picture: <strong>what actually happens when someone calls </strong><strong>/predict?</strong></p><p>I am familiar with serving ML models at work so I will use that scenario as example in the blog.</p><h3>Why Bother Understanding This?</h3><p>When I first started serving models, the goal was simple: make it work. If the endpoint returned the right prediction, that was enough. But as soon as I cared about reliability, speed, and scaling, “good enough” started to feel flimsy.</p><p>There are practical reasons to dig deeper:</p><ul><li><strong>Debugging:</strong> When an API slows down or fails, where do I even start? Is it the model? FastAPI? Uvicorn? The operating system? The network?</li><li><strong>Deployment choices:</strong> How many workers should I run? Should our endpoints be async or sync? Do I need reverse proxy or something similar in front of FastAPI?</li><li><strong>Performance tuning:</strong> Serving one model on a laptop is easy. Serving many models in production is a different story.</li></ul><p>And there’s a bigger reason: <strong>creativity</strong>.</p><p>We can’t reshape what we don’t understand. Without the fundamentals, I’ll be stuck hoping libraries keep working the way I expect. If we piece things together without really knowing how they fit, and that limits our ability to imagine new solutions.</p><p>The truth is, our FastAPI app only handles a small slice of the journey. Most of the work — networking, encryption, parsing, orchestration — happens before our code even sees the data. Once we can see that whole journey, building APIs stops feeling like magic and starts feeling like engineering.</p><p>So let’s map the high-level overview first, then walk through it step by step.</p><h3>What Happens to a Request?</h3><p>Calling /predict feels instant: the request goes out, the model runs, and a response comes back. But underneath, the journey has layers, and each layer plays a role.</p><blockquote><strong>Client → Network → Operating System → ASGI Server → FastAPI → Model → Response → Back Again</strong></blockquote><ul><li>The <strong>client</strong> (a browser, curl, or another service) starts the conversation by packaging data into a request.</li><li>The <strong>network</strong> carries that request across machines, using rules (protocols) to keep everything organized.</li><li>The <strong>operating system</strong> receives the data and exposes it to applications through something called a socket.</li><li>An <strong>ASGI server</strong> (like Uvicorn) takes that raw data, interprets it as an HTTP request, and prepares it for our app.</li><li><strong>FastAPI</strong> receives the request, validates it, and calls our function — the only part we usually think about.</li><li>The <strong>model</strong> makes a prediction and returns a result.</li><li>Then the <strong>response</strong> retraces those steps in reverse, all the way back to the client.</li></ul><p>That’s the map. Now let’s walk the path, starting with how the request even leaves the client’s machine.</p><h3>The Request Journey (High-Level Walk through)</h3><h4>The Client Creates a Request</h4><p>It begins when the client — maybe curl, maybe a browser—decides to call /predict. It needs a way to express what it wants, so it uses a <strong>protocol</strong>.</p><p>A protocol is just an agreed-upon language. HTTP, in our case, says: “Start with a verb like POST or GET, add headers to describe the request, and optionally include a body with data.”</p><p>But HTTP doesn’t actually move data. It relies on <strong>TCP</strong>, which does something simpler: it sends a stream of bytes and makes sure they arrive in the right order. That’s it. TCP doesn’t care where one message ends and another begins — it’s like sending numbered envelopes down a conveyor belt.</p><p>So the client wraps its HTTP request inside TCP and sends it off.</p><h4>Sockets and Servers</h4><p>Those bytes don’t magically appear in our FastAPI app. They land in the operating system, which gives us a <strong>socket</strong> to interact with them.</p><p>A socket is a bridge between the network and an application. Technically, it’s an interface the OS provides to send and receive data. Conceptually, it’s like a phone line: we can pick it up to hear what’s coming in, or speak into it to be heard on the other end.</p><p>But who’s holding the phone? That’s where a <strong>server</strong> comes in. A server is simply a program that waits for requests and responds to them. It listens on a specific port, picks up the socket when data arrives, and decides what to do next.</p><p>In our setup:</p><ul><li><strong>Uvicorn is the server.</strong> It listens on a port, reads bytes from the socket, and knows how to make sense of them.</li><li><strong>FastAPI is the application.</strong> It doesn’t deal with sockets or ports at all; it just waits for a request object so it can run our function.</li></ul><h4>The Operating System’s Role</h4><p>Before Uvicorn even sees those bytes, the operating system has done some heavy lifting. It collects packets from the network, reassembles them into the original byte stream, and holds them in a buffer until a program (Uvicorn) is ready to read.</p><p>This is where <strong>kernel space</strong> and <strong>user space</strong> come in:</p><ul><li>The kernel manages the hardware and network stack.</li><li>User space is where our programs run.</li></ul><p>I’ll unpack that distinction later, but for now it’s enough to know that our application only talks to the network through the OS.</p><h4>Uvicorn and ASGI Take Over</h4><p>Once Uvicorn reads the bytes from the socket, it has to figure out what they mean. Using libraries like httptools, it parses the raw stream into an HTTP request: headers, method, body. Then it turns that into an <strong>ASGI message</strong>, a standard Python format for describing requests.</p><p>It passes that message to Starlette (the framework under FastAPI), which handles routing: “Does this match /predict? If so, call the right function.”</p><h4>FastAPI Finally Sees the Request</h4><p>FastAPI takes the ASGI message, validates the input with Pydantic, and gives us something familiar: a Python object. At this point, our function runs, our model predicts, and we return a result.</p><h4>The Response Travels Back</h4><p>The response doesn’t just appear on the client. FastAPI turns our Python data into JSON, Uvicorn wraps it in HTTP, and the operating system sends it back over TCP — reversing the same layers we just walked through.</p><p>We’ve traced the journey at a high level. Each step we skimmed hides details — packets, ports, buffers, parsing, concurrency — that we’ll explore in the rest of this series.</p><h3>What’s Coming Next</h3><p>This post was about the map. Next I’ll zoom in, one layer at a time:</p><ul><li><strong>The network:</strong> What does TCP actually guarantee? How does HTTP add meaning to raw bytes? What does TLS do besides slow things down?</li><li><strong>The operating system:</strong> What really happens in kernel vs user space? Why does reading and writing cost CPU?</li><li><strong>The ASGI stack:</strong> What is Uvicorn actually doing? What makes FastAPI an application rather than a server? How does the event loop fit in?</li><li><strong>Parsing and validation:</strong> How do bytes turn into JSON and JSON into Python objects? Why is Pydantic both a safety net and a performance hit?</li><li><strong>Performance and deployment:</strong> What happens under load? How do reverse proxies and kernel tuning change the picture?</li></ul><p>The goal isn’t to memorize everything, but to build a mental model we can come back to whenever something breaks, slows down, or surprises us.</p><h3>Key Takeaways</h3><ul><li>A FastAPI endpoint feels simple because most of the work happens before our code ever runs.</li><li>A request travels through layers — client, network, operating system, server, framework — each doing its own job.</li><li>Concepts like <strong>protocols</strong>, <strong>sockets</strong>, and <strong>servers</strong>; they’re the mechanisms that make this journey possible.</li><li>FastAPI is one piece in a much bigger system: it handles application logic but not the networking or orchestration that brings the request to it.</li><li>Understanding these fundamentals gives us leverage. It helps us debug smarter, design better APIs, and think more creatively about the systems we build.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce22367157a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP) for Developers — What It Is, Why It Matters, and Where It Fits]]></title>
            <link>https://medium.com/@jayantnehra18/model-context-protocol-mcp-for-developers-what-it-is-why-it-matters-and-where-it-fits-7403155b257d?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7403155b257d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 07:04:53 GMT</pubDate>
            <atom:updated>2025-07-30T07:04:53.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Context Protocol (MCP) for Python Developers — What It Is, Why It Matters, and Where It Fits</h3><h4><strong>“Another protocol?” That’s what I thought.</strong></h4><p>When I first saw the term <em>Model Context Protocol</em> (MCP), I mostly ignored it. It felt like yet another spec in the LLM ecosystem that promised to solve everything. We were already wiring tools into our agents, passing function schemas, and calling external APIs just fine.</p><p>So why would I need a “<strong>protocol</strong>”?</p><p>It wasn’t until I saw MCP show up in OpenAI’s Agent SDK — and in several tools we actually use — that I started paying attention. But I’ll be honest: the first few times I skimmed the docs, I still couldn’t tell what MCP really <em>was</em>. Is this some Claude-specific thing? Does it replace function calling? Why does it talk about servers and clients? Can I use it in my Python backend?</p><p>These are the same questions I’m assuming you might have — and that’s why this post exists.</p><h3>What I’m doing in this post</h3><p>This isn’t a tutorial or a full walk through. You won’t be spinning up Docker containers or setting up secure deployments here.</p><p>Instead, this is about <strong>mental clarity</strong>:</p><ul><li>What exactly is MCP?</li><li>Why might it be useful — especially if you’re already building with LLMs?</li><li>How does it actually work in a real Python project?</li><li>Where does it fit into the stuff you’re probably already doing?</li></ul><p>You’ll come away with a concrete, developer-first picture of how to think about MCP and when it makes sense to use it.</p><h3>Why I Hesitated with MCP</h3><p>As a developer, I’ve seen enough “shiny new protocols” to know most aren’t worth the switch. MCP looked like another one of those. It promised a “new standard” for tool integrations — but from the outside, it seemed like function calling with extra steps.</p><p>And like many devs, I had questions:</p><ul><li>Isn’t function calling already good enough?</li><li>Why spin up a server just to expose a function?</li><li>Isn’t this something Claude uses? Does it apply to OpenAI or my own app?</li><li>Why add complexity for a local tool I could just import?</li></ul><p>I didn’t have time to figure all that out — so I ignored MCP for a while. But it didn’t go away.</p><p>Instead, it started showing up everywhere:</p><ul><li>In OpenAI’s Agent SDK</li><li>In Claude, Cursor, Windsurf</li><li>In GitHub examples from actual companies exposing useful tools via MCP servers</li></ul><p>At some point, it became clear:</p><blockquote><strong>MCP wasn’t solving something new — it was solving something <em>repetitive</em>.</strong></blockquote><h3>What finally clicked for me</h3><p>Every time I exposed a new tool to an agent, I wrote:</p><ul><li>JSON schemas</li><li>Metadata for docs</li><li>A wrapper function</li><li>Glue code to pass it to the LLM</li></ul><p>Then I did the same for the next one. And the next one.</p><p>MCP basically said:</p><ul><li>What if this part was standardized?</li><li>What if tools, resources, prompts — anything you want the LLM to use — were all exposed through a single, structured interface?</li></ul><p>That’s when I got it. MCP doesn’t change what you can do — it just <strong>makes it easier to repeat, share, and plug in anywhere. </strong>In short: it replaces your ad hoc tool-wrapping logic with a consistent interface the LLM (or the host app) can understand.</p><h3>Think of MCP like API — but for tools your LLMs can call</h3><p>With API, you define endpoints and expose them over HTTP.<br>With MCP, you define tools or resources and expose them through the <strong>model context protocol</strong> — which your LLM or host app can call.</p><p>Once this server is running, a compatible MCP client can discover the tools, inspect their schemas, and call them — just like your LLM might do through function calling.</p><p>You don’t need to handcraft JSON schemas anymore. You don’t need to think about bindings.</p><p>And because this is a <em>protocol</em>, not a framework, it doesn’t care:</p><ul><li>If you’re using OpenAI or Claude</li><li>If you’re local or remote</li><li>If your server runs in Docker, a Python file, or anywhere else</li></ul><h3>Core mental shift: tools are now servers, and your app is the client</h3><p>With MCP:</p><ul><li>Your <strong>LLM app (host)</strong> uses an <strong>MCP client</strong> to connect to one or more <strong>MCP servers</strong></li><li>Each <strong>server</strong> exposes tools/resources/prompts via a shared protocol</li><li>Everything is discoverable — tools are self-describing</li><li>You don’t need to hard-wire function definitions into your app</li></ul><p>The model (or host) chooses what to call — you just expose capabilities cleanly.</p><h3>Key Building Blocks: Host, Client, Server — and Where Your Code Lives</h3><p>MCP has a small set of moving parts, but it helps to see how they fit together — especially from a developer’s point of view.</p><h3>Host</h3><p>This is the LLM-powered application — the thing that wants to “use” a tool.</p><p>Examples:</p><ul><li>Claude Desktop or Cursor (your IDE)</li><li>OpenAI’s Agent SDK</li><li>Your own backend using an LLM to power an agent</li></ul><p>A host <strong>doesn’t implement tools</strong> — it discovers and uses them via an MCP client.</p><h3>Client</h3><p>This is the bridge.</p><p>The MCP client lives inside the host. It connects to MCP servers, discovers what tools/prompts are available, and forwards calls/responses between the host and the servers.</p><p>Most hosts (like OpenAI’s agents or Claude) already include a client. But if you’re building your own, the Python SDK lets you run one too.</p><h3>Server</h3><p>This is where your actual logic goes.</p><p>Each server defines:</p><ul><li>A set of tools (Python functions)</li><li>Optional resources (like static files)</li><li>Optional prompts (reusable instruction sets)</li></ul><p>You run the server, and the client connects to it. That’s it.</p><p>Servers can run:</p><ul><li>Locally (in dev)</li><li>Inside Docker</li><li>On a remote machine or behind an API gateway</li></ul><h3>Mental Map</h3><pre>[ Your App / LLM Agent ]  ←→  [ MCP Client ]  ←→  [ MCP Server ]  ←→  [ Your Python Function ]<br>        (Host)                   (Bridge)          (Tool Source)</pre><h3>Why MCP Might Be Worth It (Even If It Feels Like Overhead)</h3><p>Let’s be honest — at first glance, MCP feels like overengineering.</p><p>“Why not just call a Python function?”, “Why spin up a server when I can import?”</p><p>Totally fair questions.</p><p>But here’s where MCP starts to make real sense:</p><h4>Standardized, Discoverable Interfaces</h4><p>You don’t just write functions — you describe them in a machine-readable, schema-validating way <em>without writing JSON</em>.<br>Your tools become:</p><ul><li>Self-documenting</li><li>Introspectable</li><li>Versionable</li><li>Easier to plug into new clients (LLMs, agents, IDEs)</li></ul><h4>LLM-Ready</h4><p>LLMs (like Claude, GPT-4, etc.) need structured input to call tools:</p><ul><li>Parameter types</li><li>Valid options</li><li>Return shapes</li></ul><p>MCP handles this automatically from function signatures and type hints.</p><h4>Tool Sharing Between Projects</h4><p>Expose your tool once as a server — reuse it anywhere with a compatible client.<br>That’s a real upgrade for scaling, modularity, and infra reuse.</p><h4>Separation of Concerns</h4><p>With MCP, agent logic and business logic remain cleanly separated.<br>Your agent doesn’t care <em>how</em> a tool works — only that it’s available and conforms to the schema.</p><h4>Ecosystem Compatibility</h4><p>Tooling is moving in MCP’s direction:</p><ul><li>Supported in Claude, OpenAI Agents, Cursor</li><li>Actively used in LLM IDEs</li><li>SDKs available for quick setup</li><li>Server builders emerging across the ecosystem</li></ul><h3>What’s Actually Happening When an LLM Uses MCP</h3><p>To make good use of MCP, you don’t need to memorize the spec.<br>But you do need to understand what the protocol <em>actually does</em> during a tool call.</p><h4>Step 1: Agent connects to a server</h4><p>The LLM-powered host (like OpenAI’s Agent or Claude) has an MCP client built-in.<br>It connects to your MCP server and asks:</p><blockquote><em>“What tools do you have? What do they expect?”</em></blockquote><p>The server responds with a schema for each tool, generated from your Python code.</p><h4>Step 2: LLM reasons over tools</h4><p>The LLM gets the tool definitions as context and can decide when to use one.</p><h4>Step 3: Tool is invoked via the client</h4><p>The client serializes the call and sends it to your server.<br>The server executes your Python function and returns a structured response.</p><h4>Step 4: Response flows back to the LLM</h4><p>The result is sent back through the client, and the LLM resumes its reasoning with the output.</p><h3>Common Misconceptions</h3><h4>MCP replaces LangChain, CrewAI or Autogen</h4><p>No — MCP isn’t an agent framework. It doesn’t manage reasoning, orchestration, or memory. MCP is just a protocol for exposing structured tools and resources to agents that do.</p><h4>MCP makes tools smarter</h4><p>No — it makes them discoverable and schema-validating. The intelligence still comes from the LLM.</p><h4>Every tool should be an MCP tool</h4><p>Not at all. MCP is useful for reusable, externally callable logic.<br>Internal, one-off, or tightly coupled code might be better off as plain functions.</p><h4>You need to deploy everything over HTTP</h4><p>Today, MCP supports:</p><ul><li>Local development via subprocess</li><li>Remote via streamable-HTTP (pull model)</li></ul><h3>When MCP Doesn’t Make Sense</h3><ul><li>If you’re just testing ideas, plain functions are faster.</li><li>MCP tools are meant to be discoverable and callable by LLMs — don’t expose internals unnecessarily.</li><li>If you’re not scaling, sharing, or calling tools via agents — MCP may be overhead.</li></ul><p>If you’ve made it this far, you now have a solid mental model of what MCP is and why it exists. You don’t need to memorize the spec or jump into implementation right away — but next time you see it show up in a toolchain or SDK, you’ll know exactly what it’s doing and whether it fits the stack. I will write a follow up post where I’ll look at what it’s like to define real tools using the MCP Python SDK and how the pieces come together in code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7403155b257d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing HTTP Clients in Python: requests, aiohttp, and httpx]]></title>
            <link>https://python.plainenglish.io/comparing-http-clients-in-python-requests-aiohttp-and-httpx-a9ffa1caab9a?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ffa1caab9a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 08:23:08 GMT</pubDate>
            <atom:updated>2025-07-18T00:33:24.194Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past few years, I’ve worked with a number of APIs — first while integrating machine learning models into web applications, and more recently while building systems around large language models. Whether it’s model inference, logging, or streaming responses, making HTTP requests has been a routine part of that work.</p><p>In that process, I’ve used three main libraries for HTTP in Python:</p><ul><li><strong>requests</strong>: the one most developers reach for first</li><li><strong>aiohttp</strong>: built for asynchronous and concurrent workloads</li><li><strong>httpx</strong>: a newer option that supports both sync and async patterns</li></ul><p>Each of these libraries has its own design trade-offs — in terms of simplicity, performance, and flexibility. In this post, I want to walk through how they compare, based on real examples and common patterns I’ve run into.</p><p>We’ll look at:</p><ul><li>Basic request handling (GET, POST, PUT, DELETE)</li><li>How connection reuse (via sessions or clients) affects performance</li><li>Running requests concurrently with async code</li><li>And when each library starts to show its strengths or limits</li></ul><p>All examples use <a href="https://httpbin.org/">httpbin.org</a> — a simple HTTP testing service that returns helpful structured responses.</p><p>Let’s start with requests, which has probably been around the longest.</p><h3>Working with requests</h3><p>The requests library has been around for over a decade, and it remains the most widely used HTTP client in Python. Its popularity is easy to explain — it’s intuitive, clean, and hides the complexity of making HTTP requests.</p><p>Here’s a basic example of sending GET, POST, PUT, and DELETE requests using requests and the test service <a href="https://httpbin.org/">httpbin.org</a>:</p><pre>import requests<br><br>def fetch_all():<br>    base_url = &quot;https://httpbin.org&quot;<br>    res_get = requests.get(f&quot;{base_url}/get&quot;)<br>    res_post = requests.post(f&quot;{base_url}/post&quot;, json={&quot;name&quot;: &quot;Alice&quot;})<br>    res_put = requests.put(f&quot;{base_url}/put&quot;, data={&quot;status&quot;: &quot;active&quot;})<br>    res_delete = requests.delete(f&quot;{base_url}/delete&quot;)<br>    return {<br>        &quot;get&quot;: res_get.json(),<br>        &quot;post&quot;: res_post.json(),<br>        &quot;put&quot;: res_put.json(),<br>        &quot;delete&quot;: res_delete.json()<br>    }<br>results = fetch_all()<br>print(results)</pre><p><strong>output:</strong></p><pre>{<br>  &quot;get&quot;: {<br>    &quot;args&quot;: {},<br>    &quot;headers&quot;: {<br>      &quot;Accept&quot;: &quot;*/*&quot;,<br>      &quot;Accept-Encoding&quot;: &quot;gzip, deflate&quot;,<br>      &quot;Host&quot;: &quot;httpbin.org&quot;,<br>      &quot;User-Agent&quot;: &quot;python-requests/2.32.4&quot;,<br>      &quot;X-Amzn-Trace-Id&quot;: &quot;Root=1-687759e0-75e48e676cc0b68227540806&quot;<br>    },<br>    &quot;origin&quot;: &quot;103.68.42.37&quot;,<br>    &quot;url&quot;: &quot;https://httpbin.org/get&quot;<br>  },<br>  &quot;post&quot;: {<br>    &quot;args&quot;: {},<br>    &quot;data&quot;: &quot;{\&quot;name\&quot;: \&quot;Alice\&quot;}&quot;,<br>    &quot;files&quot;: {},<br>    &quot;form&quot;: {},<br>    &quot;headers&quot;: {<br>      &quot;Accept&quot;: &quot;*/*&quot;,<br>      &quot;Accept-Encoding&quot;: &quot;gzip, deflate&quot;,<br>      &quot;Content-Length&quot;: &quot;17&quot;,<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      &quot;Host&quot;: &quot;httpbin.org&quot;,<br>      &quot;User-Agent&quot;: &quot;python-requests/2.32.4&quot;,<br>      &quot;X-Amzn-Trace-Id&quot;: &quot;Root=1-687759e2-777511d92da6ee305e8fdcb3&quot;<br>    },<br>    &quot;json&quot;: {<br>      &quot;name&quot;: &quot;Alice&quot;<br>    },<br>    &quot;origin&quot;: &quot;103.68.42.37&quot;,<br>    &quot;url&quot;: &quot;https://httpbin.org/post&quot;<br>  },<br>  &quot;put&quot;: {<br>    ...<br>  },<br>  &quot;delete&quot;: {<br>    ...<br>  }<br>}</pre><blockquote><strong><em>Each of these requests is made one after the other — and each one opens a new connection under the hood. For simple use cases, that’s fine. But the more requests you send, the more noticeable the overhead becomes.</em></strong></blockquote><p>In the next section, we’ll look at how reusing connections can improve performance, even when using the same requests library.</p><h3>Improving requests with Sessions</h3><p>By default, requests creates a new HTTP connection every time you send a request. That works, but it&#39;s not very efficient — especially if you&#39;re calling the same host repeatedly. Creating and tearing down connections introduces latency that can be avoided.</p><p>To address this, requests provides a Session object. A session manages a connection pool behind the scenes, allowing connections to be reused across multiple requests. This small change can noticeably reduce total request time, particularly in scripts that make several calls in a row.</p><p>Here’s how the same example looks when using a session:</p><pre>import requests<br><br>def fetch_all_with_session():<br>    base_url = &quot;https://httpbin.org&quot;<br>    session = requests.Session()<br>    res_get = session.get(f&quot;{base_url}/get&quot;)<br>    res_post = session.post(f&quot;{base_url}/post&quot;, json={&quot;name&quot;: &quot;Alice&quot;})<br>    res_put = session.put(f&quot;{base_url}/put&quot;, data={&quot;status&quot;: &quot;active&quot;})<br>    res_delete = session.delete(f&quot;{base_url}/delete&quot;)<br>    return {<br>        &quot;get&quot;: res_get.json(),<br>        &quot;post&quot;: res_post.json(),<br>        &quot;put&quot;: res_put.json(),<br>        &quot;delete&quot;: res_delete.json()<br>    }<br>results = fetch_all_with_session()<br>print(results)</pre><blockquote><strong>The output will follow the same structure as before, but you’ll likely notice a shorter execution time. In practice, using a session can cut the total runtime nearly in half — especially if the server supports persistent connections.</strong></blockquote><p>This change doesn’t affect the shape of the response at all. What changes is how efficiently those responses are retrieved. Connection reuse might seem like an implementation detail, but when your application is under load or calling APIs frequently, it can make a measurable difference.</p><p>Sessions are easy to adopt and require very little structural change. But they don’t solve the fact that requests still handles calls sequentially. If each request waits for the previous one to finish, there’s a ceiling to how fast your code can go — even with connection pooling. That’s where concurrency comes in.</p><h3>Why Concurrency Matters</h3><p>When we send HTTP requests one at a time, we end up waiting unnecessarily — especially when the requests are independent. This is common in real applications: calling multiple endpoints, fetching resources in parallel, or posting batch updates. There’s no reason to wait for one call to complete before sending the next, unless the order truly matters.</p><p>The requests library runs everything synchronously. That means each request blocks the program until it finishes. With four independent API calls, you&#39;re effectively adding up their latencies.</p><p>Here’s a simplified view:</p><pre>[GET] -----&gt; [POST] -----&gt; [PUT] -----&gt; [DELETE]</pre><p>Now imagine we could fire all four requests off at once, and just wait for them to return — regardless of order:</p><pre>[GET]   [POST]   [PUT]   [DELETE]<br>   \      |        |       /<br>    [Wait for all responses]</pre><blockquote>This is where <strong>asynchronous</strong> libraries come in. They allow the program to issue requests concurrently and resume processing once each one completes — without waiting on others.</blockquote><p>In workloads where API latency is significant — or where we’re working with dozens of calls — this can make a noticeable difference. It’s not about doing more work faster; it’s about not sitting idle while the network does its thing.</p><p>In the next section, we’ll look at how aiohttp makes this possible by building around Python’s async capabilities from the start.</p><h3>Using aiohttp for Concurrent Requests</h3><p>aiohttp is built specifically for asynchronous workloads. Unlike requests, it doesn&#39;t just support concurrency — it expects it. If you&#39;re writing code that can benefit from sending multiple requests at once, aiohttp is a strong candidate.</p><p>Here’s a version of the same four requests using aiohttp with async functions. This example uses httpbin.org just like before:</p><pre>import aiohttp<br>import asyncio<br><br>async def fetch_all():<br>    base_url = &quot;https://httpbin.org&quot;<br>    async with aiohttp.ClientSession() as session:<br>        async with session.get(f&quot;{base_url}/get&quot;) as res_get:<br>            data_get = await res_get.json()<br>        async with session.post(f&quot;{base_url}/post&quot;, json={&quot;name&quot;: &quot;Alice&quot;}) as res_post:<br>            data_post = await res_post.json()<br>        async with session.put(f&quot;{base_url}/put&quot;, data={&quot;status&quot;: &quot;active&quot;}) as res_put:<br>            data_put = await res_put.json()<br>        async with session.delete(f&quot;{base_url}/delete&quot;) as res_delete:<br>            data_delete = await res_delete.json()<br>    return {<br>        &quot;get&quot;: data_get,<br>        &quot;post&quot;: data_post,<br>        &quot;put&quot;: data_put,<br>        &quot;delete&quot;: data_delete<br>    }<br>results = asyncio.run(fetch_all())<br>print(results)</pre><p>Example response structure (get entry shown as a sample):</p><pre>{<br>  &quot;args&quot;: {},<br>  &quot;headers&quot;: {<br>    &quot;Accept&quot;: &quot;*/*&quot;,<br>    &quot;Host&quot;: &quot;httpbin.org&quot;,<br>    &quot;User-Agent&quot;: &quot;Python/3.12 aiohttp/3.9.5&quot;,<br>    &quot;X-Amzn-Trace-Id&quot;: &quot;Root=1-6878f781-1c8b157d34aa4e7031e3ac25&quot;<br>  },<br>  &quot;origin&quot;: &quot;103.68.42.37&quot;,<br>  &quot;url&quot;: &quot;https://httpbin.org/get&quot;<br>}</pre><p><strong>The pattern here is different from </strong><strong>requests in two ways:</strong></p><ol><li>Every network call is wrapped in async with, which ensures proper connection handling.</li><li>Each request must be awaited, which makes the function non-blocking — it gives control back to the event loop while the network call is in progress.</li></ol><p>By default, aiohttp uses sessions and connection pooling. So you&#39;re getting both performance and concurrency benefits out of the box — but it comes with more boilerplate and a stricter structure.</p><p>If your application is already async (like a FastAPI backend), aiohttp fits in naturally. Otherwise, you’ll have to introduce asyncio concepts just to take advantage of the library — which can be a heavier lift if you&#39;re not using async elsewhere.</p><p>In the next section, we’ll look at httpx, which takes a middle path: it works like requests, but supports async when you need it.</p><h3>How httpx Bridges Both Worlds</h3><p>httpx is a newer library that brings a modern interface to HTTP requests in Python. What makes it interesting is that it supports both synchronous and asynchronous APIs — meaning you can start with code that looks like requests, and later opt into async features if your application needs them.</p><p>Here’s what a basic synchronous version looks like using httpx:</p><pre>import httpx<br><br>def fetch_all():<br>    base_url = &quot;https://httpbin.org&quot;<br>    client = httpx.Client()<br>    res_get = client.get(f&quot;{base_url}/get&quot;)<br>    res_post = client.post(f&quot;{base_url}/post&quot;, json={&quot;name&quot;: &quot;Alice&quot;})<br>    res_put = client.put(f&quot;{base_url}/put&quot;, data={&quot;status&quot;: &quot;active&quot;})<br>    res_delete = client.delete(f&quot;{base_url}/delete&quot;)<br>    return {<br>        &quot;get&quot;: res_get.json(),<br>        &quot;post&quot;: res_post.json(),<br>        &quot;put&quot;: res_put.json(),<br>        &quot;delete&quot;: res_delete.json()<br>    }<br>results = fetch_all()<br>print(results)</pre><p>This version behaves almost identically to the session-based example with requests, but under the hood, it uses a more modern connection model and HTTP/1.1/2 support.</p><p>Example response (post entry shown as sample):</p><pre>{<br>  &quot;args&quot;: {},<br>  &quot;data&quot;: &quot;{\&quot;name\&quot;: \&quot;Alice\&quot;}&quot;,<br>  &quot;files&quot;: {},<br>  &quot;form&quot;: {},<br>  &quot;headers&quot;: {<br>    &quot;accept&quot;: &quot;*/*&quot;,<br>    &quot;accept-encoding&quot;: &quot;gzip, deflate, br&quot;,<br>    &quot;content-length&quot;: &quot;17&quot;,<br>    &quot;content-type&quot;: &quot;application/json&quot;,<br>    &quot;host&quot;: &quot;httpbin.org&quot;,<br>    &quot;user-agent&quot;: &quot;python-httpx/0.27.0&quot;,<br>    &quot;x-amzn-trace-id&quot;: &quot;Root=1-6878f89c-4f4e9f7b263c0d464c3a3d4b&quot;<br>  },<br>  &quot;json&quot;: {<br>    &quot;name&quot;: &quot;Alice&quot;<br>  },<br>  &quot;origin&quot;: &quot;103.68.42.37&quot;,<br>  &quot;url&quot;: &quot;https://httpbin.org/post&quot;<br>}</pre><p>You still get the performance benefit of connection reuse via the Client, and the API surface stays familiar. If you&#39;ve written requests code before, switching to httpx in synchronous mode requires very few changes.</p><p>But where httpx becomes especially useful is when you&#39;re ready to make those calls concurrently. It lets you switch to an AsyncClient, keeping the rest of your code largely intact — we’ll look at that next.</p><h3>Running Requests Concurrently with httpx</h3><p>To enable concurrency with httpx, you switch from using a regular Client to an AsyncClient. This gives you access to non-blocking behavior using Python’s async and await syntax — much like aiohttp, but with less boilerplate and a more familiar API if you&#39;re coming from requests.</p><p>Here’s how the same four requests can be issued concurrently using httpx.AsyncClient and asyncio.gather:<br>A simple HTTP Request &amp; Response S</p><pre>import httpx<br>import asyncio<br><br><br>async def fetch_all():<br>    base_url = &quot;https://httpbin.org&quot;<br>    async with httpx.AsyncClient() as client:<br>        tasks = [<br>            client.get(f&quot;{base_url}/get&quot;),<br>            client.post(f&quot;{base_url}/post&quot;, json={&quot;name&quot;: &quot;Alice&quot;}),<br>            client.put(f&quot;{base_url}/put&quot;, data={&quot;status&quot;: &quot;active&quot;}),<br>            client.delete(f&quot;{base_url}/delete&quot;)<br>        ]<br>        res_get, res_post, res_put, res_delete = await asyncio.gather(*tasks)<br>    return {<br>        &quot;get&quot;: res_get.json(),<br>        &quot;post&quot;: res_post.json(),<br>        &quot;put&quot;: res_put.json(),<br>        &quot;delete&quot;: res_delete.json()<br>    }<br>results = asyncio.run(fetch_all())<br>print(results)</pre><blockquote><strong>This approach lets all four requests go out at once. Python’s event loop manages the waits in the background, and responses are gathered as they come in — not one after another.</strong></blockquote><p>Sample response (delete entry shown):</p><pre>{<br>  &quot;args&quot;: {},<br>  &quot;data&quot;: &quot;&quot;,<br>  &quot;files&quot;: {},<br>  &quot;form&quot;: {},<br>  &quot;headers&quot;: {<br>    &quot;accept&quot;: &quot;*/*&quot;,<br>    &quot;accept-encoding&quot;: &quot;gzip, deflate, br&quot;,<br>    &quot;content-length&quot;: &quot;0&quot;,<br>    &quot;host&quot;: &quot;httpbin.org&quot;,<br>    &quot;user-agent&quot;: &quot;python-httpx/0.27.0&quot;,<br>    &quot;x-amzn-trace-id&quot;: &quot;Root=1-6878f9c1-70db2cc3707b9f0d4b66e405&quot;<br>  },<br>  &quot;json&quot;: null,<br>  &quot;origin&quot;: &quot;103.68.42.37&quot;,<br>  &quot;url&quot;: &quot;https://httpbin.org/delete&quot;<br>}</pre><p>If you’re measuring the total time for the function to run, you’ll likely see it come in well under one second — much faster than the synchronous version. The difference becomes even more dramatic as the number of calls increases.</p><p>This is especially useful in applications like LLM-based tools or multi-model orchestration, where multiple independent APIs are queried for results, embeddings, or metadata. As long as your requests don’t depend on each other’s output, concurrency helps you reclaim wait time and keep your app responsive.</p><blockquote>It’s worth noting that you still need to be cautious with rate limits. Sending too many requests in parallel to the same API can quickly hit throttling thresholds. Most APIs document their rate-limiting policies — and it’s a good idea to respect them.</blockquote><h3>Personal Recommendation</h3><p>Over the past few months, I’ve been using httpx almost exclusively in my work — especially while building applications that interact with language models and other remote services. It’s become my preferred choice not just for the performance, but for how little friction it introduces.</p><p>What makes httpx stand out is the way it balances <strong>familiarity</strong> with <strong>flexibility</strong>. I can start with a simple synchronous get() call — just like I would with requests — and later move to async without rewriting the whole flow or switching libraries. That kind of transition matters when you&#39;re iterating quickly or when a small prototype grows into something production-facing.</p><p>With aiohttp, I’d get great concurrency and performance, but at the cost of more boilerplate and stricter patterns. It works well, but feels heavier for many use cases — especially when I don’t need the extra control it offers.</p><p>So while all three libraries have their place, httpx has struck the right balance in my projects — it gives me clean syntax, modern features, and async support when I need it, without forcing me to commit to complexity from the start.</p><p>That flexibility has made a real difference in how I design systems that talk to external APIs, especially when responsiveness matters.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ffa1caab9a" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/comparing-http-clients-in-python-requests-aiohttp-and-httpx-a9ffa1caab9a">Comparing HTTP Clients in Python: requests, aiohttp, and httpx</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class Initialization in Python]]></title>
            <link>https://medium.com/@jayantnehra18/class-initialization-in-python-490ff3cef10f?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/490ff3cef10f</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 07:03:40 GMT</pubDate>
            <atom:updated>2025-07-02T07:03:40.756Z</atom:updated>
            <content:encoded><![CDATA[<p>When we create an object from a class in Python, we often think of that action as a single step — but Python is actually doing two things behind the scenes:</p><ol><li>It creates the new object.</li><li>Then it initializes that object’s internal state.</li></ol><p>These two phases — <strong>instantiation</strong> and <strong>initialization</strong> — happen every time we write something like user = User().</p><p>This post is about what those phases mean, what Python does automatically, and how we can hook into the process using the __init__ method. It’s not just a convention — __init__ is Python’s built-in way of letting us customize how objects are initialized right after they’re created.</p><p>I’ll use a simple User class throughout to keep examples clear and practical. Let’s start by looking at what Python actually does when we instantiate a class.</p><h3>What Happens When We Instantiate a Class</h3><p>Python classes are callable. That means when we write something like User(), Python isn’t just returning an object — it’s running a sequence of steps to produce and prepare that object.</p><p>Let’s define a simple class:</p><pre>class User:<br>    role = &quot;member&quot;</pre><pre>user = User()</pre><p>Here’s what happens when User() is called:</p><ol><li><strong>Python creates a new instance of </strong><strong>User.</strong> This is just a fresh object in memory.</li><li><strong>An empty instance namespace is initialized.</strong> This is where attributes unique to that object will live — it starts as an empty dictionary.</li></ol><p>We can confirm that the object is created by printing or inspecting it:</p><pre>print(user)<br># &lt;__main__.User object at 0x...&gt;</pre><p>At this point, the object exists — it’s an instance of User — but it doesn’t yet have any instance-specific data. Unless we explicitly add something, it only inherits from the class.</p><p>That’s where __init__ comes in.</p><h3>The Role of __init__: Initialization After Creation</h3><p>Python gives us a way to set up an object right after it’s created: the __init__ method.</p><p>Let’s define it inside our User class:</p><pre>class User:<br>    def __init__(self, name):<br>        self.name = name</pre><p>Now when we create an instance:</p><pre>user = User(&quot;Jayant&quot;)</pre><p>Python runs two steps under the hood:</p><ol><li>It creates the User object (this is instantiation).</li><li>It calls __init__ on that object with &quot;Jayant&quot; as an argument (this is initialization):</li></ol><pre>User.__init__(user, &quot;Jayant&quot;)</pre><p>That’s why __init__ is often referred to as the initializer. It’s not responsible for creating the object — it’s just configuring it after creation.</p><p>Inside __init__, we typically assign values to instance attributes using self. These assignments don’t go into the class — they go into the new object’s own namespace.</p><h3>self and the Instance Namespace</h3><p>Inside __init__, self is the newly created object. When we assign attributes to self, we’re populating that object’s personal namespace.</p><p>Let’s expand our example:</p><pre>class User:<br>    role = &quot;member&quot;  # Class-level attribute<br><br>    def __init__(self, name, email):<br>            self.name = name<br>            self.email = email</pre><p>Now:</p><pre>user = User(&quot;Jayant&quot;, &quot;Jayant@example.com&quot;)<br>print(user.__dict__)<br># {&#39;name&#39;: &#39;Jayant&#39;, &#39;email&#39;: &#39;Jayant@example.com&#39;}</pre><p>Here’s what’s happening:</p><ul><li>role lives in the class, so it’s shared across all users unless overridden.</li><li>name and email are set on the instance, and they show up in the instance’s __dict__ — that’s its internal namespace.</li></ul><p>If we try to access role, Python will first look in the instance’s __dict__, not find it, and then fall back to the class:</p><pre>print(user.role)<br># member</pre><p>But name and email are found directly on the instance.</p><p>This is the pattern we rely on when writing most Python classes: use __init__ to populate each object’s unique state, while using class attributes for shared defaults or constants. Let&#39;s look at a full example and compare this to a two-step setup process without __init__.</p><h3>Example: Tracking User Info with __init__</h3><p>Let’s bring this all together with a complete example:</p><pre>class User:<br>    def __init__(self, name, email):<br>        self.name = name<br>        self.email = email<br><br>user = User(&quot;Jayant&quot;, &quot;Jayant@example.com&quot;)<br>print(user.__dict__)<br># {&#39;name&#39;: &#39;Jayant&#39;, &#39;email&#39;: &#39;Jayant@example.com&#39;}</pre><p>The __init__ method allows us to initialize the object in a single step. We create the instance <em>and</em> populate its attributes at the same time.</p><p>Compare that to doing it manually, in two steps:</p><pre>class User:<br>    def setup(self, name, email):<br>        self.name = name<br>        self.email = email<br><br><br>user = User()<br>user.setup(&quot;Jayant&quot;, &quot;Jayant@example.com&quot;)<br>print(user.__dict__)<br># {&#39;name&#39;: &#39;Jayant&#39;, &#39;email&#39;: &#39;Jayant@example.com&#39;}</pre><p>Functionally, this gives us the same result. But Python gives us __init__ to make this process automatic and consistent. As soon as we instantiate the object, Python calls __init__ for us with the arguments we provide.</p><p>This is what allows us to create fully-formed objects in one line — and what makes object-oriented design in Python more predictable and readable. There is a lesser-used part of the instantiation process: __new__.</p><h3>Quick Note on __new__</h3><p>So far we’ve been talking about __init__, which handles object <strong>initialization</strong>. But before Python ever calls __init__, it first has to <strong>create</strong> the object — and that’s where __new__ comes in.</p><p>Here’s how the full flow looks:</p><ol><li>Python calls __new__ to create the new object.</li><li>Then it calls __init__ to initialize that object.</li></ol><p>By default, we don’t need to define __new__ ourselves. It’s implemented by the base object class, and it usually just returns a new, empty instance.</p><p>We typically only override __new__ in special cases — like when working with immutable types (e.g., tuple, str) or customizing object creation in frameworks or metaclasses.</p><p>For example, this is valid but rarely needed:</p><pre>class User:<br>    def __new__(cls, *args, **kwargs):<br>        print(&quot;Creating a new User instance&quot;)<br>        return super().__new__(cls)<br><br>    def __init__(self, name):<br>            print(&quot;Initializing User&quot;)<br>            self.name = name<br>    <br>user = User(&quot;Jayant&quot;)<br># Creating a new User instance<br># Initializing User</pre><p>Unless we have a reason to intercept object creation itself, we stick to __init__. That’s where almost all of the practical, initialization happens in Python classes.</p><h3>What Python Really Does When You Create an Object</h3><p>When we call something like User(&quot;Jayant&quot;, &quot;Jayant@example.com&quot;), Python is doing a bit more than it lets on.</p><p>Under the hood:</p><ol><li>It creates a new object — that’s the role of __new__.</li><li>It immediately initializes that object — that’s where __init__ comes in.</li></ol><p>And __init__ isn’t just a setup hook. It’s part of Python’s core protocol for object-oriented design. When we define it, we’re saying: “Every time someone creates an instance of this class, here’s how it should be initialized.”</p><p>What makes this predictable is that Python applies the same pattern across the board — whether we’re creating a user-defined object or something built-in like a list or str. The methods may differ, but the life cycle is the same: first creation, then initialization.</p><p>That’s why writing classes in Python often starts with __init__ — not because it’s required, but because it’s where the behavior of each instance begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490ff3cef10f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method Binding in Python]]></title>
            <link>https://python.plainenglish.io/method-binding-in-python-37ebb25df241?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ebb25df241</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 10:44:02 GMT</pubDate>
            <atom:updated>2025-07-01T01:05:22.204Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with classes in Python, we’re used to assigning attributes like numbers, strings, or lists — straightforward data. But when the attribute is a <strong>function</strong>, Python handles it differently. That difference is subtle at first glance, but it changes how our code behaves when accessed through instances.</p><p>Take this example:</p><pre>class MyClass:<br>    def say_hello():<br>        print(&quot;Hello world&quot;)</pre><p>Here, say_hello is defined inside the class. At this point, it&#39;s just a function — nothing more. But if we create an instance of MyClass and try to call that same attribute:</p><pre>my_object = MyClass()<br>my_object.say_hello()</pre><p>we’ll get a TypeError:</p><pre>TypeError: say_hello() takes 0 positional arguments but 1 was given</pre><p>So where is that extra argument coming from?”</p><p>The short answer is that Python is doing something on our behalf — and unless we account for it, this kind of error is easy to run into.</p><p>This post will walk through what’s actually happening when functions are defined in classes, how Python binds them to instances, and what it means when a function becomes a <strong>bound method</strong>.</p><p>Let’s start with the basics.</p><h3>Functions as Class Attributes</h3><p>Let’s start by defining a simple class with a function inside it:</p><pre>class MyClass:<br>    def say_hello():<br>        print(&quot;Hello world&quot;)</pre><p>At this stage, say_hello is a function defined inside a class body — nothing more. If we inspect it directly via the class, Python treats it as a plain function:</p><pre>MyClass.say_hello<br># &lt;function MyClass.say_hello at 0x...&gt;</pre><p>So far, there’s no binding involved. The class simply holds a reference to a function object, and that’s what we get when we access it directly.</p><p>Now let’s create an instance:</p><pre>my_object = MyClass()</pre><p>And access the same attribute, this time through the instance:</p><pre>my_object.say_hello<br># &lt;bound method MyClass.say_hello of &lt;__main__.MyClass object at 0x...&gt;&gt;</pre><p>This is where things shift — without us changing the code. What we now have is not just a function, but a <strong>bound method</strong>: a callable that knows which instance it’s tied to. The method has been automatically linked (or “bound”) to my_object, the instance we just created.</p><p>We can confirm that by inspecting it explicitly:</p><pre>type(MyClass.say_hello)<br># &lt;class &#39;function&#39;&gt;<br><br>type(my_object.say_hello)<br># &lt;class &#39;method&#39;&gt;</pre><p><strong>So where is that extra argument coming from?</strong></p><p>Same attribute name, same definition — but different behavior depending on how it’s accessed. The class keeps the function; the instance gets a method. Python handles that distinction internally, and that’s the mechanism we’ll explore next.</p><h3>Instances and Bound Methods</h3><p>When we access a function through an instance, Python doesn’t just return the function — it returns a <strong>method object</strong>. This object still behaves like a function (we can call it), but it also carries additional context: the instance it’s bound to.</p><p>We can see this more clearly in the following example:</p><pre>class MyClass:<br>    def say_hello():<br>        print(&quot;Hello world&quot;)</pre><pre>my_object = MyClass()</pre><p>Now, calling my_object.say_hello() gives us:</p><pre>my_object.say_hello()<br># TypeError: say_hello() takes 0 positional arguments but 1 was given</pre><p>But we didn’t pass any arguments — at least not explicitly. What’s going on?</p><p>This is Python inserting the instance (my_object) as the first argument to the function call. It does this automatically when we access a function from an instance. The method call:</p><pre>my_object.say_hello()</pre><p>is interpreted as:</p><pre>MyClass.say_hello(my_object)</pre><p>And since the original function wasn’t defined to accept any arguments, we get a TypeError.</p><p>Let’s rewrite the method properly:</p><pre>class MyClass:<br>    def say_hello(self):<br>        print(&quot;Hello world&quot;)</pre><pre>my_object = MyClass()<br>my_object.say_hello()<br># Output: Hello world</pre><p>By adding self to the method signature, we’re telling Python: “Yes, this function expects to be called with an instance — and here’s where to receive it.”</p><p>That’s the core idea behind method binding. Functions defined in a class become methods when accessed from an instance. And bound methods automatically receive the instance as their first argument.</p><h3>Why Bound Methods Matter</h3><p>At this point, we’ve seen that when a function is accessed through an instance, Python passes the instance as the first argument automatically. That’s what makes a function turn into a <em>bound method</em>. But let’s be more precise about what Python is actually doing here.</p><p>Suppose we define:</p><pre>class MyClass:<br>    def say_hello(self):<br>        print(&quot;Hello world&quot;)</pre><pre>my_object = MyClass()</pre><p>When we write:</p><pre>my_object.say_hello()</pre><p>Python interprets it like this under the hood:</p><pre>MyClass.say_hello(my_object)</pre><p>This automatic passing of my_object as the first argument is why we need to include self in the method definition. If we leave it out, as we saw earlier, Python still injects the instance — and the call fails due to an unexpected argument.</p><p>This also explains why functions assigned directly to instances behave differently. Consider this:</p><pre>my_object.other_func = lambda: print(&quot;Hello from instance&quot;)<br>my_object.other_func()<br># Output: Hello from instance</pre><p>Even though we attached the function to the instance, Python doesn’t treat it as a method. No automatic binding occurs, and no arguments are injected. That lambda remains a plain function — not a method — because Python didn’t create it through class definition.</p><p>Bound methods matter because they preserve the relationship between the instance and the function logic. They allow methods to access the instance (self), its attributes, and any custom behavior specific to that particular object.</p><p>This mechanism is what makes object-oriented behavior in Python work the way it does.</p><p>In the next section, we’ll look more closely at the internal structure of a bound method — and see how we can inspect what exactly is bound.</p><h3>Behind the Scenes: __func__ and __self__</h3><p>A bound method in Python isn’t just a callable — it’s an object that keeps track of both the original function and the instance it’s bound to. We can see this clearly by inspecting two special attributes every bound method carries:</p><ul><li>__func__: the original function defined in the class</li><li>__self__: the instance the method is bound to</li></ul><p>Let’s walk through an example:</p><pre>class MyClass:<br>    def say_hello(self):<br>        print(f&quot;Hello from {self}&quot;)</pre><pre>my_object = MyClass()<br>bound_method = my_object.say_hello</pre><p>Now we can inspect the pieces:</p><pre>print(bound_method.__func__)<br># &lt;function MyClass.say_hello at 0x...&gt;</pre><pre>print(bound_method.__self__)<br># &lt;__main__.MyClass object at 0x...&gt;</pre><p>This confirms what we saw earlier:</p><ul><li>bound_method.__func__ is the original say_hello function as defined in MyClass</li><li>bound_method.__self__ is the instance my_object</li></ul><p>This also explains why method calls behave the way they do. When we write:</p><pre>my_object.say_hello()</pre><p>it’s equivalent to this:</p><pre>my_object.say_hello.__func__(my_object.say_hello.__self__)</pre><p>or even more directly:</p><pre>MyClass.say_hello(my_object)</pre><p>Python uses the bound method’s internal structure to route the call, insert the instance, and invoke the original function.</p><p>Knowing about __func__ and __self__ isn’t something we need every day, but it’s useful for debugging, introspection, and dynamic behavior — like reusing methods or inspecting call targets.</p><p>In the next section, we’ll explore how this plays out when instances override attributes or when classes share methods but customize their behavior.</p><h3>Example: Dynamic Attribute Behavior</h3><p>Now that we have covered how bound methods work, let’s look at how they interact with attributes — especially when class and instance attributes overlap. Let’s consider a class that models users with roles:</p><pre>class User:<br>    role = &quot;guest&quot;<br>    <br>    def greet(self):<br>        return f&quot;Welcome, {self.role}!&quot;</pre><p>We define a default role (guest) at the class level. Now we create two instances:</p><pre>u1 = User()<br>u2 = User()<br>u2.role = &quot;admin&quot;<br><br>print(u1.greet())  # Welcome, guest!<br>print(u2.greet())  # Welcome, admin!</pre><p>Here’s what’s happening:</p><ul><li>u1 uses the default role from the class because it doesn’t have a role attribute of its own.</li><li>u2 has its role set directly on the instance, so self.role resolves to &quot;admin&quot;.</li></ul><p>Even though both instances are using the same method greet, the bound method adapts to the instance it’s tied to. Python evaluates self.role at runtime for each instance:</p><ul><li>In u1.greet(), self is u1, so Python finds role on the class.</li><li>In u2.greet(), self is u2, and Python finds the overridden attribute on the instance.</li></ul><p>This highlights two things:</p><ul><li>Bound methods always refer to the instance (self) they’re called on.</li><li>Attribute lookup checks the instance first, then the class — every time.</li></ul><p>We’re not doing anything dynamic or tricky here — just relying on Python’s built-in method binding and attribute resolution model. But these fundamentals are what make class-based behavior flexible and powerful.</p><h3>Dynamic Method Assignment (Monkey Patching)</h3><p>In Python, we can modify classes or instances at runtime — even adding new methods on the fly. This practice is often called <em>monkey patching</em>, and it gives us a useful way to explore how method binding really works.</p><p>Let’s start with this:</p><pre>class User:<br>    def greet(self):<br>        return &quot;Hello&quot;</pre><p>We can add a new method directly to the class after it’s been defined:</p><pre>def promote(self):<br>    return f&quot;{self} has been promoted!&quot;<br><br>User.promote = promote<br>u = User()<br>print(u.promote())<br># Output: &lt;__main__.User object at 0x...&gt; has been promoted!</pre><p>Python treats promote as a method because we attached it to the class. When we call u.promote(), Python binds the instance (u) to the method, so self works as expected.</p><p>But what happens if we attach a function directly to an instance?</p><pre>u.other_action = lambda: &quot;Custom action&quot;<br>print(u.other_action())<br># Output: Custom action</pre><p>This time, Python doesn’t bind anything automatically. The lambda is just a plain function. There’s no self parameter involved, and no binding occurs — because it was added directly to the instance, not the class.</p><p>This distinction matters:</p><ul><li>Functions added to <strong>classes</strong> are treated as methods.</li><li>Functions added to <strong>instances</strong> are just functions.</li></ul><p>If we ever want to manually bind a function to an instance, we can do it using the types.MethodType helper — but under normal circumstances, class definitions handle this automatically for us.</p><p>Understanding this behavior is important when we’re debugging dynamic code, extending third-party classes, or modifying behavior during tests.</p><h3>To Recap</h3><p>When a function is defined inside a class, Python treats it as just that — a function — until we access it through an instance. At that point, it becomes a <strong>bound method</strong>, which:</p><ul><li>Automatically receives the instance as the first argument (self)</li><li>Stores the instance internally via __self__</li><li>Retains a reference to the original function via __func__</li></ul><p>We also looked at how attribute lookup works in tandem with method binding:</p><ul><li>Python checks for attributes on the instance first, then on the class.</li><li>Class-level functions become bound methods when accessed through an instance.</li><li>Functions added directly to instances stay unbound — they don’t receive self.</li></ul><p>This isn’t about memorizing internals — it’s about knowing what Python is doing so that we can write clearer, more predictable code. Whether we’re working with built-in types or our own classes, the same rules apply.</p><p>For example, when we call “hello”.upper(), we’re calling a method on a <em>str instance</em> — and Python is injecting that string instance as self into the underlying implementation of upper.</p><p><strong>The same applies to lists, dictionaries, file objects, and most things in the standard library. And that’s what makes the language consistent.</strong></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ebb25df241" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/method-binding-in-python-37ebb25df241">Method Binding in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Python Projects That Scale: Structure, Imports, and Dependencies]]></title>
            <link>https://python.plainenglish.io/writing-python-projects-that-scale-structure-imports-and-dependencies-d496f985db3a?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d496f985db3a</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[toml]]></category>
            <category><![CDATA[uv]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Wed, 07 May 2025 07:27:01 GMT</pubDate>
            <atom:updated>2025-05-08T15:21:48.985Z</atom:updated>
            <content:encoded><![CDATA[<p>As Python projects grow beyond quick scripts and notebooks, small structural decisions start to matter. What begins as a single file can quickly evolve into a collection of data loaders, models, and utilities — each with their own dependencies and responsibilities. Without a clear structure, even simple tasks like importing a module or reproducing an environment can become unexpectedly fragile.</p><p>This guide is for developers who are comfortable writing Python code but are looking to improve how they structure, share, and maintain their projects. It covers how to set up a modern Python project using a clear layout, the pyproject.toml standard, and the uv dependency manager. Along the way, it explains the reasoning behind each choice—how it helps avoid common problems and supports long-term maintainability.</p><p>The goal is not to prescribe a rigid standard, but to provide a set of practical tools and concepts that can scale with your work. Whether you’re working solo or collaborating with others, this structure will help keep your projects clean, reproducible, and easier to work with over time.</p><h3>Common Issues in Unstructured Projects</h3><p>Many Python projects begin informally — files are added as needed, dependencies grow organically, and folder layouts emerge without much planning. While this flexibility is part of Python’s appeal, it often leads to friction as the project matures.</p><p>Here are some recurring issues that surface in such setups:</p><h4>• Fragile Imports</h4><p>Code that works when run from one folder may break in another. You might find yourself adjusting sys.path, using relative imports like from ..utils import, or duplicating functions across files just to get things working.</p><h4>• Confusing Project Roots</h4><p>Without a consistent entry point or defined structure, it becomes unclear what the “root” of the project is — especially for tools like Jupyter, pytest, or CLI scripts. This leads to mismatched behavior depending on where and how the code is run.</p><h4>• Dependency Drift</h4><p>Using only a requirements.txt generated by pip freeze mixes application dependencies with transient and platform-specific ones. The result is a brittle file that may work on one machine and fail on another.</p><h4>• Difficult Reuse and Collaboration</h4><p>Without a clear package structure or installation mechanism, other developers (or even your future self) may struggle to reuse parts of the project — especially across notebooks, scripts, or services.</p><h3>Project Layout: Using src/ to Avoid Import Conflicts</h3><p>A consistent project layout helps Python locate your modules reliably — regardless of how or where the project is executed. One of the most effective patterns for this is placing all importable code under a dedicated src/ directory.</p><h3>Why the src/ Layout?</h3><p>Consider this structure:</p><pre>my_project/<br>├── src/<br>│   └── my_package/<br>│       ├── __init__.py<br>│       ├── encoder.py<br>│       └── utils.py<br>├── tests/<br>│   └── test_encoder.py<br>├── pyproject.toml<br>└── README.md</pre><p>Here, all source code lives under src/my_package/. This layout enforces a clean boundary between your importable code and everything else—tests, configuration, documentation, etc.</p><h3>How This Prevents Common Issues</h3><ul><li><strong>Import conflicts:</strong> Python doesn’t accidentally import from the current directory or sibling folders. It only sees what has been explicitly installed into the environment.</li><li><strong>Reliable behavior in notebooks and tests:</strong> Notebooks or test runners launched from different folders will still locate your modules if the project is installed (even in editable mode).</li><li><strong>Safer packaging and distribution:</strong> Tools like setuptools can scan src/ and install only the intended code, reducing packaging errors.</li></ul><h3>When Does This Layout Help?</h3><p>Even for solo projects, this structure pays off as soon as:</p><ul><li>You split code into multiple files</li><li>You want to write reusable modules</li><li>You use tools like pytest, Jupyter, or command-line entry points</li></ul><p>In short, the src/ layout prevents subtle bugs that arise from Python’s import system, especially when projects grow or get reused in different contexts.</p><h3>Defining the Project with pyproject.toml</h3><p>The pyproject.toml file is the central configuration file for modern Python projects. It replaces older combinations of setup.py, setup.cfg, and requirements.txt with a unified, declarative format.</p><h4>Core Purpose</h4><ul><li>Declares project metadata (name, version, description)</li><li>Lists top-level dependencies</li><li>Defines entry points for CLI tools</li><li>Informs the build system (e.g., setuptools, poetry, or hatch) how to package and install the project</li></ul><h4>Minimal Example</h4><pre>[project]<br>name = &quot;my-package&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;A text embedding benchmarking tool&quot;<br>requires-python = &quot;&gt;=3.10&quot;<br>dependencies = [<br>  &quot;pandas&quot;,<br>  &quot;scikit-learn&quot;,<br>  &quot;sentence-transformers&quot;,<br>  &quot;pyyaml&quot;,<br>  &quot;tqdm&quot;<br>]</pre><p>This section is used both by dependency managers like uv and by build tools like setuptools.</p><h3>Defining CLI Commands</h3><p>Projects that expose command-line functionality can use the [project.scripts] section:</p><pre>[project.scripts]<br>run-benchmark = &quot;my_package.cli:main&quot;</pre><p>This allows users to run your tool like this:</p><pre>run-benchmark --config config.yml</pre><p>…as long as the project has been installed (e.g. via uv pip install -e .).</p><h3>Declaring Package Structure</h3><p>To make the src/ layout work properly, you also need to add:</p><pre>[tool.setuptools]<br>package-dir = {&quot;&quot; = &quot;src&quot;}</pre><pre>[tool.setuptools.packages.find]<br>where = [&quot;src&quot;]</pre><p>This tells setuptools to look inside src/ when building the package and registering importable modules.</p><h3>Making Code Importable: Editable Installs</h3><p>In a structured project, you want to be able to import your own modules reliably during development without copying or reinstalling them every time you make a change. This is where <strong>editable installs</strong> come in.</p><h3>What Is an Editable Install?</h3><p>An editable install tells Python:</p><blockquote><em>“Treat this source code as a package — even if it’s not zipped or built — so I can import it and run it from anywhere.”</em></blockquote><p>This is done using:</p><pre>uv pip install -e .</pre><p>The -e flag means <strong>editable</strong>, and the . refers to the current directory (your project root).</p><h3>What Happens Behind the Scenes?</h3><ol><li>setuptools reads your pyproject.toml and finds your code under src/my_package/</li><li>It creates a small file called an <strong>egg-link</strong> in your virtual environment</li><li>That file points back to your local source directory</li></ol><p>As a result:</p><ul><li>You can import your package (e.g. from my_package import encoder) from any script, notebook, or test</li><li>You don’t need to adjust sys.path or use fragile relative imports</li><li>Code changes are reflected immediately without reinstalling the package</li></ul><h3>Why This Matters</h3><p>Without an editable install, imports often break when:</p><ul><li>Running Jupyter notebooks from a notebooks/ folder</li><li>Running tests from the project root</li><li>Using CLI tools that rely on proper Python module discovery</li></ul><p>Editable installs make your code behave like a first-class package during development — without requiring a build step.</p><h3>Managing Dependencies with uv</h3><p>Managing dependencies consistently is essential for reproducibility — whether you’re working across machines, sharing code, or running pipelines in production. The uv tool provides a modern alternative to older workflows based on requirements.txt and pip freeze.</p><h3>Defining Dependencies in pyproject.toml</h3><p>Instead of maintaining a requirements.txt, you declare your top-level dependencies directly:</p><pre>[project]<br>dependencies = [<br>  &quot;pandas&quot;,<br>  &quot;scikit-learn&quot;,<br>  &quot;sentence-transformers&quot;,<br>  &quot;pyyaml&quot;<br>]</pre><p>This keeps your dependencies version-controlled, structured, and easy to maintain alongside your project metadata.</p><h3>Installing and Locking Dependencies</h3><p>Use uv to install and lock dependencies:</p><pre>uv pip install         # Installs from pyproject.toml<br>uv pip install -e .    # Installs your package in editable mode</pre><p>This automatically generates a uv.lock file, which captures:</p><ul><li>Exact versions of all direct and transitive dependencies</li><li>Platform-specific variations</li><li>Hashes for security verification</li></ul><h3>Reproducing the Environment</h3><p>Anyone with access to your repository can then run:</p><pre>uv sync</pre><p>This installs the exact environment from uv.lock, ensuring that:</p><ul><li>All packages are pinned to tested versions</li><li>There are no surprises due to upstream updates</li><li>The project works the same across machines, CI, or deployment environments</li></ul><h3>Do You Still Need requirements.txt?</h3><p>Not when using uv. The uv.lock file replaces requirements.txt and pip freeze workflows.</p><p>The only exception is when dealing with older tools that require a requirements.txt, in which case you can generate one from the lock file if needed—but for most workflows, it&#39;s no longer necessary.</p><h3>Recap and Key Takeaways</h3><p>Python projects benefit from a clear structure, consistent dependency management, and predictable behavior across tools and environments. Here’s a summary of the key practices covered:</p><h4>Structure</h4><ul><li>Use a src/ layout to isolate your importable code</li><li>Keep tests, configs, and experiments outside the package</li><li>Avoid relative imports and manual path manipulation</li></ul><h4>Configuration</h4><ul><li>Use pyproject.toml as the single source of truth</li><li>Declare metadata, dependencies, and entry points explicitly</li><li>Include tool.setuptools blocks to support the src/ layout</li></ul><h4>Development Workflow</h4><ul><li>Use uv pip install -e . to make your project importable in-place</li><li>This enables consistent imports across scripts, notebooks, and tools</li></ul><h4>Dependency Management</h4><ul><li>Define top-level dependencies in pyproject.toml</li><li>Let uv handle installation and lock file creation</li><li>Commit uv.lock to enable reproducible environments with uv sync</li></ul><p>By adopting these practices early, projects will become easier to maintain, test, and share. They also scale better as complexity increases — whether that means adding contributors, introducing automation, or publishing tools internally.</p><p>This foundation prepares project for future improvements like automated testing, formatting, and CI workflows — which can be layered on incrementally.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d496f985db3a" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/writing-python-projects-that-scale-structure-imports-and-dependencies-d496f985db3a">Writing Python Projects That Scale: Structure, Imports, and Dependencies</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Python Dependencies with uv]]></title>
            <link>https://python.plainenglish.io/managing-python-dependencies-with-uv-e6d2c52fd488?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d2c52fd488</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 10:54:00 GMT</pubDate>
            <atom:updated>2025-04-30T06:53:21.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*36snFXkszSYRLXXd" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Dependency management is an essential part of working with Python projects. When dependencies are not handled correctly, even a simple package update can break an entire project.</p><p>Traditionally, developers have relied on <strong>pip and requirements.txt</strong>, but these tools have several limitations:</p><ul><li>Dependencies can conflict, requiring <strong>manual resolution</strong>.</li><li>Installing packages on different machines can lead to <strong>inconsistent environments</strong>.</li><li>pip freeze &gt; requirements.txt captures exact versions, but does <strong>not guarantee reproducibility</strong> across systems.</li></ul><p>Tools like <strong>Poetry</strong> aimed to improve this by introducing a structured pyproject.toml and better dependency resolution. However, Poetry is <strong>slow</strong> and often overkill for projects that don’t need its package publishing features.</p><p>This is where <strong>uv</strong> comes in. uv is a modern dependency manager that is <strong>faster than pip and Poetry</strong>, handles <strong>automatic virtual environments</strong>, and makes <strong>dependency management predictable</strong>.</p><h3>Why pip &amp; requirements.txt Fall Short</h3><p>If you’ve worked on Python projects long enough, you’ve likely run into problems like:</p><h4><strong>The Same </strong><strong>pip install -r requirements.txt Produces Different Results</strong></h4><ul><li>requirements.txt lists dependencies, but it <strong>doesn’t lock down sub-dependencies</strong>.</li><li>If a package updates upstream, your install might resolve to a different version.</li><li><strong>Outcome:</strong> You get different environments on different machines, leading to “works on my machine” issues.</li></ul><h4><strong>Conflicting Dependencies Are Hard to Resolve Manually</strong></h4><ul><li>If two packages require different versions of the same library, pip will <strong>either fail or install the latest version</strong>, which can break things.</li><li>There’s no built-in mechanism to resolve conflicts before installing.</li></ul><h4><strong>Virtual Environments Need Manual Setup</strong></h4><ul><li>You have to remember to create and activate a venv.</li><li>Installing dependencies without one can <strong>pollute your global environment</strong>.</li></ul><h4><strong>No Standardized Project Structure</strong></h4><ul><li>requirements.txt is just a flat list of packages—there’s no built-in way to define <strong>metadata, Python versions, or optional dependencies</strong>.</li></ul><p>Instead of relying on requirements.txt and manual venv management, uv provides <strong>a structured, repeatable approach to managing Python projects</strong>.</p><h3>Setting Up Python Dependencies with uv</h3><p>Let’s walk through setting up a <strong>Python data pipeline</strong> using uv. This project will:</p><ul><li><strong>Extract data from a REST API using </strong><strong>dlt.</strong></li><li><strong>Store the extracted data in DuckDB.</strong></li><li><strong>Use </strong><strong>uv to manage dependencies efficiently.</strong></li></ul><h3>Installing uv</h3><p>The best way to install uv is via pipx to keep it isolated from system packages:</p><pre>pipx install uv</pre><p>To verify installation:</p><pre>uv --version</pre><h3>Initializing the Project</h3><p>Instead of manually creating a virtual environment, uv can initialize a structured project:</p><pre>uv init</pre><p>This does three things:</p><ol><li><strong>Creates a </strong><strong>pyproject.toml file</strong> – The modern way to define dependencies.</li><li><strong>Sets up an automatic virtual environment</strong> — No need to manage venv manually.</li><li><strong>Prepares the project for reproducible builds.</strong></li></ol><h3>Defining Dependencies in pyproject.toml</h3><p>Unlike requirements.txt, pyproject.toml provides <strong>structured dependency management</strong>. Here’s an example:</p><pre>[project]<br>name = &quot;rest_api_pipeline&quot;<br>version = &quot;0.1.0&quot;<br>dependencies = [<br>    &quot;dlt&quot;,<br>    &quot;duckdb&quot;<br>]<br>requires-python = &quot;&gt;=3.8&quot;<br><br>[tool.uv]<br>virtualenvs.in-project = true  # Store venv inside the projectuv remove duckdb</pre><p>Key differences from requirements.txt:</p><ul><li><strong>Dependencies are explicitly structured.</strong></li><li><strong>Python version requirements are included.</strong></li><li><strong>Additional project metadata is stored cleanly.</strong></li></ul><h3>Adding Dependencies with uv</h3><p>To install dependencies and update pyproject.toml:</p><pre>uv add dlt duckdb</pre><p>Unlike pip install, uv add ensures:</p><ul><li><strong>All dependencies are compatible</strong> before installing them.</li><li><strong>Versions are written to </strong><strong>pyproject.toml automatically.</strong></li></ul><h3>uv remove duckdbLocking Dependencies with uv.lock</h3><p>Lockfiles are essential for <strong>ensuring that every environment installs the same package versions</strong>.</p><h3>Generating a Lockfile</h3><pre>uv lock</pre><p>This creates a uv.lock file, which <strong>pins exact versions of all dependencies and their sub-dependencies</strong>.</p><h3>Installing from a Lockfile</h3><p>On a new machine, instead of running pip install -r requirements.txt, simply run:</p><pre>uv sync</pre><p>This ensures that <strong>all dependencies match the versions in </strong><strong>uv.lock</strong>, preventing unexpected changes.</p><h3>Why uv.lock Matters</h3><ul><li>Tracks direct dependencies</li><li>Tracks sub-dependencies</li><li>Guarantees same install on every machine|</li><li>Prevents accidental upgrades</li></ul><p>If <strong>exact reproducibility</strong> matters — especially in production — using uv.lock is the best approach.</p><h3>Managing Dependencies in Production</h3><p>Once your project is set up, here are best practices for maintaining clean dependency management:</p><h4>1. Keep Dependencies Locked in Production</h4><ul><li>Always generate a uv.lock file after installing new dependencies:</li></ul><pre>uv lock</pre><ul><li>Deployments should always install from uv.lock:</li></ul><pre>uv sync</pre><h4>2. Removing Dependencies Cleanly</h4><ul><li>To uninstall a package while ensuring dependencies remain intact:</li></ul><pre>uv remove duckdb</pre><h3>Migrating from pip or Poetry to uv</h3><p>If you’re currently using pip with requirements.txt, migrating to uv is straightforward:</p><pre>uv init<br>uv add -r requirements.txt<br>uv lock</pre><p>For Poetry users, uv reads pyproject.toml natively, so it’s just a matter of switching commands.</p><p>Dependency management in Python is often overlooked until it <strong>breaks a project</strong>. Using uv instead of pip or Poetry brings several key advantages:</p><ul><li><strong>Faster installs and dependency resolution.</strong></li><li><strong>Automatic virtual environment management.</strong></li><li><strong>Reproducible environments with </strong><strong>uv.lock.</strong></li><li><strong>Cleaner, structured dependencies in </strong><strong>pyproject.toml.</strong></li></ul><p>For production-ready <strong>data pipelines, APIs, and machine learning workflows</strong>, uv provides a more reliable and scalable approach.</p><p>If you’re still using pip + requirements.txt, <strong>switching to </strong><strong>uv is an easy way to improve reproducibility and speed up your development workflow</strong>.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d2c52fd488" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/managing-python-dependencies-with-uv-e6d2c52fd488">Managing Python Dependencies with uv</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expanding My Snowflake Data Pipeline: External Stages, External Tables, and Materialized Views]]></title>
            <link>https://medium.com/@jayantnehra18/expanding-my-snowflake-data-pipeline-external-stages-external-tables-and-materialized-views-482756b50ed1?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/482756b50ed1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 07:54:19 GMT</pubDate>
            <atom:updated>2025-02-02T07:54:19.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Expanding Snowflake Data Pipeline: External Stages, External Tables, and Materialized Views</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89_jlIAkVmSEEnIaKC22RQ.png" /></figure><p>In my first Snowflake experimentation, I built a <strong>data pipeline that ingested CSV files using internal stages</strong>. The pipeline included loading data into Snowflake, merging it into a final table, generating summarized insights, and scheduling everything with Snowflake Tasks.</p><p>While this worked well for a structured batch-processing approach, I wanted to explore a <strong>more scalable way to integrate cloud storage with Snowflake</strong>.</p><p>In this session, I focused on:</p><ul><li><em>Ingesting data from cloud storage (Azure Blob Storage) into Snowflake using external stages.</em></li><li><em>Understanding how Snowflake prevents duplicate data loads.</em></li><li><em>Using external tables to query staged data directly without loading it into Snowflake tables.</em></li><li><em>Creating materialized views to improve query performance on external data.</em></li></ul><p>This blog documents my experimentation and the step-by-step process of integrating Snowflake with external cloud storage for efficient data ingestion and processing.</p><h3>Recap of My First Data Pipeline</h3><p>In my <strong>previous session</strong>, I worked with <strong>internal stages</strong>, which store files <strong>inside Snowflake</strong> before loading them into tables. Here’s a quick summary of what I built:</p><ul><li>Uploaded CSV files to an internal stage and ingested data using COPY INTO.</li><li>Created a file format to properly interpret the data structure.</li><li>Merged staged data into a target table while ensuring uniqueness.</li><li>Aggregated daily order data for reporting.</li><li>Scheduled everything with Snowflake Tasks to automate the pipeline.</li></ul><p>While this approach worked well, I wanted to explore how Snowflake interacts with <strong>external cloud storage providers like Azure, AWS, and GCP</strong> to handle <strong>large-scale data ingestion</strong> efficiently.</p><blockquote><strong>I have covered this in previous blog </strong><a href="https://medium.com/@jayantnehra18/building-a-data-pipeline-in-snowflake-cloud-kitchen-scenario-43a8d0c95406"><strong>Building a Data Pipeline in Snowflake: Cloud Kitchen Scenario</strong></a></blockquote><h3>Setting Up External Stages for Cloud Storage Integration</h3><h4>What Are External Stages?</h4><p>A <strong>stage</strong> in Snowflake is a pointer to a file location where data is stored before ingestion. <strong>External stages</strong> reference <strong>cloud storage locations</strong>, such as <strong>Azure Blob Storage, Amazon S3, or Google Cloud Storage</strong>, rather than storing files inside Snowflake.</p><p>This approach is useful for <strong>big data ingestion</strong> because:</p><ul><li>It <strong>reduces storage costs</strong> by keeping raw files in cloud storage.</li><li>Snowflake can <strong>query external data directly</strong> without ingestion.</li><li>It allows <strong>seamless integration with existing cloud pipelines</strong>.</li></ul><h4>Creating a Storage Integration with Azure Blob Storage</h4><p>To connect Snowflake to <strong>Azure Blob Storage</strong>, we need to create a <strong>storage integration</strong>. This integration allows Snowflake to <strong>access cloud storage securely</strong> without storing credentials inside SQL scripts.</p><pre>USE ROLE ACCOUNTADMIN;<br>CREATE STORAGE INTEGRATION AZ_CK_INTEGRATION <br>TYPE = EXTERNAL_STAGE <br>STORAGE_PROVIDER = &#39;AZURE&#39; <br>ENABLED = TRUE <br>AZURE_TENANT_ID = &#39;your-azure-tenant-id&#39;<br>STORAGE_ALLOWED_LOCATIONS = (&#39;azure://cloudkitchen.blob.core.windows.net/orderfiles&#39;);</pre><p>Once the integration is created, we <strong>grant access to the SYSADMIN role</strong> so we can use it in later steps:</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT USAGE ON INTEGRATION AZ_CK_INTEGRATION TO ROLE SYSADMIN;<br>USE ROLE SYSADMIN;</pre><h4>Creating an External Stage</h4><p>After setting up the storage integration, we define an <strong>external stage</strong> pointing to the cloud storage location:</p><pre>CREATE STAGE AZ_CK_STAGE <br>STORAGE_INTEGRATION = AZ_CK_INTEGRATION <br>URL = &#39;azure://cloudkitchen.blob.core.windows.net/orderfiles&#39;;</pre><p>To verify that Snowflake can access the files, we use:</p><pre>LIST @AZ_CK_STAGE;</pre><p>If files are successfully listed, the integration is working, and we can proceed with <strong>loading data</strong>.</p><h3>Loading Data from External Storage into a Staging Table</h3><h4>Creating a Staging Table</h4><p>Before ingesting the data, we define a staging table where the raw data will be stored:</p><pre>USE DATABASE CLOUD_KITCHEN_DB;<br>USE SCHEMA RAW_ORDERS_AZ;</pre><pre>CREATE OR REPLACE TABLE ORDERS_STG (<br>    customer VARCHAR,<br>    order_date DATE,<br>    delivery_date DATE,<br>    item_type VARCHAR,<br>    quantity NUMBER,<br>    source_file VARCHAR,<br>    load_timestamp TIMESTAMP<br>);</pre><h4>Using COPY INTO to Load Data</h4><p>We then use the <strong>COPY INTO</strong> command to load data from Azure Blob Storage into the ORDERS_STG table:</p><pre>COPY INTO ORDERS_STG<br>FROM (<br>    SELECT $1, $2, $3, $4, $5, METADATA$FILENAME, CURRENT_TIMESTAMP<br>    FROM @AZ_CK_STAGE<br>) <br>FILE_FORMAT = (TYPE = CSV, SKIP_HEADER = 1) <br>ON_ERROR = ABORT_STATEMENT;</pre><h3>Avoiding Duplicate Data Loads</h3><h4>How Snowflake Prevents Duplicate Loads</h4><ul><li>Snowflake <strong>tracks metadata</strong> for each staged file to prevent duplicate loads.</li><li>If the same file is staged <strong>and already loaded</strong>, running COPY INTO again will not reload it.</li></ul><p>To verify if a file was loaded:</p><pre>SELECT * <br>FROM INFORMATION_SCHEMA.LOAD_HISTORY <br>WHERE SCHEMA_NAME = &#39;RAW_ORDERS_AZ&#39; <br>AND TABLE_NAME = &#39;ORDERS_STG&#39; <br>ORDER BY LAST_LOAD_TIME DESC;</pre><h4>Forcing a Reload of Files</h4><p>If we want to reload all files <strong>regardless of metadata tracking</strong>, we use:</p><pre>COPY INTO ORDERS_STG <br>FROM @AZ_CK_STAGE <br>FILE_FORMAT = (TYPE = CSV, SKIP_HEADER = 1) <br>FORCE = TRUE;</pre><h3>Querying External Data Without Loading It</h3><h4>Using External Tables</h4><p>Instead of loading data into Snowflake, <strong>external tables</strong> allow querying data <strong>directly from cloud storage</strong>.</p><pre>CREATE OR REPLACE EXTERNAL TABLE RAW_ORDERS_EXT (<br>    customer VARCHAR AS (VALUE:c1::VARCHAR),<br>    order_date DATE AS (VALUE:c2::DATE),<br>    delivery_date DATE AS (VALUE:c3::DATE),<br>    item_type VARCHAR AS (VALUE:c4::VARCHAR),<br>    quantity NUMBER AS (VALUE:c5::NUMBER),<br>    source_file VARCHAR AS METADATA$FILENAME<br>) LOCATION = @AZ_CK_STAGE <br>AUTO_REFRESH = FALSE <br>FILE_FORMAT = RAW_ORDERS_CSV_FORMAT;</pre><p>Now, we can run:</p><pre>SELECT * FROM RAW_ORDERS_EXT;</pre><p>External tables are <strong>cheaper</strong> but have <strong>slower query performance</strong> than internal tables.</p><h3>Improving Performance with Materialized Views</h3><p>Since external tables are <strong>slow</strong>, we can create a <strong>materialized view</strong> to store a snapshot of the data <strong>inside Snowflake</strong> for better query performance.</p><pre>CREATE OR REPLACE MATERIALIZED VIEW RAW_ORDERS_MV AS<br>SELECT <br>    customer,<br>    order_date,<br>    delivery_date,<br>    item_type,<br>    quantity,<br>    source_file<br>FROM RAW_ORDERS_EXT;</pre><p>Now, we query the materialized view instead of the external table:</p><pre>SELECT * FROM RAW_ORDERS_MV;</pre><p>This approach <strong>improves performance</strong> because the materialized view <strong>persists data inside Snowflake</strong>, while still being automatically updated when the external table is refreshed.</p><h3>Final Thoughts</h3><p>This session helped me expand my <strong>Snowflake pipeline</strong> by exploring:</p><blockquote><strong>Ingesting data from Azure Blob Storage into Snowflake using external stages</strong>.</blockquote><blockquote><strong>Using external tables to query data directly from cloud storage</strong>.</blockquote><blockquote><strong>Preventing duplicate loads with Snowflake’s metadata tracking</strong>.</blockquote><blockquote><strong>Improving query performance with materialized views</strong>.</blockquote><p>This method is <strong>useful for large-scale cloud data pipelines</strong>, reducing storage costs while keeping Snowflake <strong>integrated with cloud-based storage systems</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=482756b50ed1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Data Pipeline in Snowflake: Cloud Kitchen Scenario]]></title>
            <link>https://medium.com/@jayantnehra18/building-a-data-pipeline-in-snowflake-cloud-kitchen-scenario-43a8d0c95406?source=rss-4dfcfb6b38a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a8d0c95406</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jayant Nehra]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 05:44:03 GMT</pubDate>
            <atom:updated>2025-02-02T05:44:03.928Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89_jlIAkVmSEEnIaKC22RQ.png" /></figure><p>As someone with experience working with <strong>BigQuery and data warehouses</strong>, I was already familiar with concepts like query optimization, data modeling, and large-scale data processing. However, when I started exploring <strong>Snowflake</strong>, I wanted to go beyond just writing queries and understand <strong>how its object model works, how to set up a structured workflow, and how to efficiently manage data ingestion and transformations</strong>.</p><p>My goal was to get hands-on experience with Snowflake’s <strong>database setup, staging, data loading, and transformation processes</strong>. To structure my learning, I used a <strong>Cloud Kitchen scenario</strong> where customer orders are ingested, stored, and processed into summarized reports. This gave me a practical way to experiment with <strong>Snowflake’s internal stages, COPY INTO for data loading, MERGE for handling updates, and task scheduling for automation</strong>.</p><p>This blog walks through that journey — setting up Snowflake from scratch, understanding its key components, and working through common data engineering tasks.</p><p>If you’re new to Snowflake or looking for a structured approach to learning its features, this guide should provide a good starting point.</p><h3>Understanding Roles in Snowflake</h3><p>Snowflake follows a <strong>role-based access control (RBAC)</strong> system to manage permissions for users and objects. A <strong>role</strong> determines what actions a user can perform, such as creating databases, querying tables, or managing warehouses.</p><h3>Common Roles in Snowflake</h3><p>Snowflake comes with predefined roles, each with different levels of access:</p><ol><li><strong>ACCOUNTADMIN</strong> — The highest privilege level, allowing full access to all objects and administrative tasks.</li><li><strong>SYSADMIN</strong> — Used for creating and managing databases, schemas, and warehouses. This role has control over data-related objects but does not manage user access.</li><li><strong>SECURITYADMIN</strong> — Manages users, roles, and access control but does not create or modify data objects.</li><li><strong>USERADMIN</strong> — Manages users and role assignments.</li><li><strong>PUBLIC</strong> — A default role that all users have access to, but with very limited privileges.</li></ol><h3>Why Use SYSADMIN Instead of ACCOUNTADMIN?</h3><p>In the setup script, we use <strong>SYSADMIN</strong> instead of <strong>ACCOUNTADMIN</strong> for database and schema creation:</p><pre>USE ROLE SYSADMIN;<br>CREATE DATABASE CLOUD_KITCHEN_DB;<br>CREATE SCHEMA ORDERS;<br>CREATE WAREHOUSE CLOUD_KITCHEN_WH WITH WAREHOUSE_SIZE = &#39;XSMALL&#39;;</pre><p>While <strong>ACCOUNTADMIN</strong> has full control over all operations, it is best practice to use a <strong>lower-privileged role</strong> like <strong>SYSADMIN</strong> for managing databases and warehouses. This ensures security and minimizes the risk of accidental changes to critical account-level settings.</p><p>However, some actions — such as <strong>granting permissions on a warehouse</strong> — require <strong>ACCOUNTADMIN</strong> privileges. That’s why we temporarily switch to the <strong>ACCOUNTADMIN</strong> role before granting privileges to <strong>SYSADMIN</strong>:</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT ALL PRIVILEGES ON WAREHOUSE CLOUD_KITCHEN_WH TO ROLE SYSADMIN;</pre><p>By following this approach, we maintain a <strong>secure and structured access control model</strong>, ensuring that different roles have the appropriate level of permissions.</p><h3>Exploring Snowflake Through a Cloud Kitchen Experiment</h3><h4>Setting Up the Cloud Kitchen Database</h4><p>Before working with data, we first need to set up <strong>Snowflake objects</strong>:</p><ul><li><strong>Database</strong> — A logical container to organize schemas and tables</li><li><strong>Schema</strong> — A sub-container within a database that holds tables and views</li><li><strong>Warehouse</strong> — The compute layer that runs SQL queries and processes data</li></ul><p>To begin, we create a <strong>database, schema, and virtual warehouse</strong> in Snowflake using the following commands:</p><pre>USE ROLE SYSADMIN;<br>CREATE DATABASE CLOUD_KITCHEN_DB;<br>CREATE SCHEMA ORDERS;<br>CREATE WAREHOUSE CLOUD_KITCHEN_WH WITH WAREHOUSE_SIZE = &#39;XSMALL&#39;;</pre><p>Each component plays a specific role:</p><ul><li>The <strong>database (</strong><strong>CLOUD_KITCHEN_DB)</strong> will contain all tables related to this project.</li><li>The <strong>schema (</strong><strong>ORDERS)</strong> groups tables logically within the database.</li><li>The <strong>warehouse (</strong><strong>CLOUD_KITCHEN_WH)</strong> is required to execute queries. The size is set to &#39;XSMALL&#39; to optimize cost.</li></ul><p>After creating these objects, we grant privileges to allow the <strong>SYSADMIN role</strong> to manage the warehouse:</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT ALL PRIVILEGES ON WAREHOUSE CLOUD_KITCHEN_WH TO ROLE SYSADMIN;</pre><p>Now that our database environment is ready, we can move on to <strong>staging data for ingestion</strong>.</p><h3>Creating a Staging Area for Data Upload</h3><p>Snowflake uses <strong>stages</strong> as a temporary holding area for files before they are loaded into tables. There are two types of stages:</p><ol><li><strong>Internal Stage</strong> — Stored inside Snowflake</li><li><strong>External Stage</strong> — Stored in AWS S3, Azure Blob Storage, or Google Cloud Storage</li></ol><p>For this project, I created an <strong>internal stage (</strong><strong>ORDERS_STAGE)</strong> to hold the order data:</p><pre>USE DATABASE CLOUD_KITCHEN_DB;<br>USE SCHEMA ORDERS;<br>CREATE STAGE ORDERS_STAGE;</pre><p>We can now upload CSV files to this stage using the <strong>Snowflake UI (Snowsight)</strong> or command-line tools. To verify that the files have been successfully uploaded, we use:</p><pre>LIST @ORDERS_STAGE;</pre><p>At this point, the data is staged but not yet loaded into a table. The next step is to inspect the staged data and handle <strong>header rows</strong>, which Snowflake does not automatically differentiate from data.</p><h3>Querying Staged Data &amp; Handling Headers</h3><p>Once the data is staged, we can query it to check its structure:</p><pre>SELECT $1, $2, $3, $4, $5 FROM @ORDERS_STAGE;</pre><p>However, Snowflake <strong>does not automatically detect headers</strong> in CSV files, meaning the first row (which contains column names) is treated as data. To fix this, we define a <strong>file format</strong> that tells Snowflake to skip headers when loading data:</p><pre>CREATE FILE FORMAT my_csv_format<br>  TYPE = &#39;CSV&#39;<br>  SKIP_HEADER = 1;</pre><p>Now, we can query the staged data while ensuring the header row is ignored:</p><pre>SELECT $1, $2, $3, METADATA$FILENAME <br>FROM @ORDERS_STAGE (FILE_FORMAT =&gt; my_csv_format);</pre><p>Here, the <strong>METADATA$FILENAME</strong> column is useful because it captures the name of the uploaded file, which helps with tracking and debugging.</p><p>Now that we understand how the staged data looks, the next step is to load it into a <strong>staging table</strong>.</p><h3>Loading Data into a Staging Table</h3><p>Rather than loading data directly into a final table, it’s a best practice to use an <strong>intermediate staging table</strong>. This allows us to apply transformations before inserting data into the target table.</p><p>We create the <strong>staging table (</strong><strong>ORDERS_STG)</strong>, including metadata columns to store the file name and the timestamp of ingestion:</p><pre>CREATE OR REPLACE TABLE ORDERS_STG (<br>    customer VARCHAR,<br>    order_date DATE,<br>    delivery_date DATE,<br>    item_type VARCHAR,<br>    quantity NUMBER,<br>    source_file VARCHAR,<br>    load_timestamp TIMESTAMP<br>);</pre><p>Now, we are ready to load data into this table.</p><h3>Using COPY INTO for Efficient Loading</h3><p>The <strong>COPY INTO</strong> command is the recommended way to load large volumes of data in Snowflake. It allows us to:</p><ul><li>Extract data from the <strong>staged file</strong></li><li>Skip the <strong>header row</strong></li><li>Capture the <strong>filename</strong> for tracking</li><li>Handle errors gracefully</li></ul><p>We execute the <strong>COPY INTO</strong> command:</p><pre>COPY INTO ORDERS_STG FROM (<br>    SELECT $1, $2, $3, $4, $5, METADATA$FILENAME, CURRENT_TIMESTAMP<br>    FROM @ORDERS_STAGE<br>)<br>FILE_FORMAT = (TYPE=CSV, SKIP_HEADER=1)<br>ON_ERROR = ABORT_STATEMENT<br>PURGE = TRUE;</pre><p>Here’s what each option does:</p><ul><li><strong>SKIP_HEADER=1</strong> → Ensures the header row is ignored</li><li><strong>ON_ERROR=ABORT_STATEMENT</strong> → Stops execution if errors occur</li><li><strong>PURGE=TRUE</strong> → Deletes the file from the stage after successful ingestion</li></ul><p>At this point, the <strong>staging table is populated</strong> with data from the CSV file.</p><h3>Merging Staged Data into the Target Table</h3><p>Now that the staged data is loaded into ORDERS_STG, the next step is to merge it into the final CUSTOMER_ORDERS table. Instead of simply inserting all records, we need to <strong>handle updates intelligently</strong>.</p><p>A common scenario in data engineering is when <strong>customers modify their orders</strong>. If a customer places an order and later changes the quantity for the same item type on the same delivery date, we want to <strong>update the existing order</strong> rather than insert a duplicate.</p><h3>Creating the Target Table</h3><p>The target table will store finalized customer orders, ensuring each record has the latest information.</p><pre>CREATE OR REPLACE TABLE CUSTOMER_ORDERS (<br>    customer VARCHAR,<br>    order_date DATE,<br>    delivery_date DATE,<br>    item_type VARCHAR,<br>    quantity NUMBER,<br>    source_file VARCHAR,<br>    load_timestamp TIMESTAMP<br>);</pre><h3>Using MERGE for Upsert Logic</h3><p>The <strong>MERGE INTO</strong> statement allows us to update existing records when a match is found or insert new ones if no match exists.</p><pre>MERGE INTO CUSTOMER_ORDERS TGT <br>USING ORDERS_STG AS SRC<br>ON  <br>    SRC.CUSTOMER = TGT.CUSTOMER<br>    AND SRC.DELIVERY_DATE = TGT.DELIVERY_DATE<br>    AND SRC.ITEM_TYPE = TGT.ITEM_TYPE<br>WHEN MATCHED THEN<br>    UPDATE SET <br>        TGT.QUANTITY = SRC.QUANTITY,<br>        TGT.SOURCE_FILE = SRC.SOURCE_FILE,<br>        TGT.LOAD_TIMESTAMP = CURRENT_TIMESTAMP()<br>WHEN NOT MATCHED THEN <br>    INSERT (CUSTOMER, ORDER_DATE, DELIVERY_DATE, ITEM_TYPE, QUANTITY, SOURCE_FILE, LOAD_TIMESTAMP)<br>    VALUES (SRC.CUSTOMER, SRC.ORDER_DATE, SRC.DELIVERY_DATE, SRC.ITEM_TYPE, SRC.QUANTITY, SRC.SOURCE_FILE, CURRENT_TIMESTAMP());</pre><h3>Why Use MERGE Instead of INSERT?</h3><ul><li><strong>Ensures uniqueness</strong> → Prevents duplicate orders for the same customer and item type.</li><li><strong>Updates existing records</strong> → If a customer modifies an order, it reflects in the table.</li><li><strong>Maintains auditability</strong> → We track when the data was updated using CURRENT_TIMESTAMP().</li></ul><p>Once the <strong>merge is complete</strong>, the CUSTOMER_ORDERS table will always have the most up-to-date order details.</p><h3>Summarizing Data for Business Insights</h3><p>After processing raw order data, it’s common to create <strong>aggregated summaries</strong> for reporting and analytics.</p><h4>Creating a Summary Table</h4><p>The summary table will store <strong>daily item sales</strong> for easy analysis.</p><pre>CREATE OR REPLACE TABLE SUMMARY_ORDERS (<br>    DELIVERY_DATE DATE, <br>    ITEM_TYPE VARCHAR, <br>    TOTAL_QUANTITY NUMBER<br>);</pre><h4>Populating the Summary Table</h4><p>We aggregate the total quantity of each item type per delivery date.</p><pre>INSERT INTO SUMMARY_ORDERS (DELIVERY_DATE, ITEM_TYPE, TOTAL_QUANTITY)<br>SELECT DELIVERY_DATE, ITEM_TYPE, SUM(QUANTITY) <br>FROM CUSTOMER_ORDERS<br>GROUP BY DELIVERY_DATE, ITEM_TYPE;</pre><p>This table allows quick access to summarized order data without querying the full orders dataset every time.</p><h3>Automating Everything with Snowflake Tasks</h3><p>To keep data up to date, we automate the <strong>entire pipeline</strong> using <strong>Snowflake Tasks</strong>.</p><h4>What Are Snowflake Tasks?</h4><p>Snowflake Tasks allow <strong>scheduled execution of SQL statements</strong>, automating ingestion, transformations, and summarization.</p><h4>Creating a Scheduled Task</h4><p>The following task will:</p><ol><li><strong>Truncate the staging table</strong> to remove old data.</li><li><strong>Load new data using COPY INTO</strong>.</li><li><strong>Merge the data into the target table</strong>.</li><li><strong>Truncate and repopulate the summary table</strong>.</li></ol><pre>CREATE TASK SUMMARIZE_ORDERS <br>    WAREHOUSE = CLOUD_KITCHEN_WH<br>    SCHEDULE = &#39;1 M&#39;<br>AS <br>BEGIN <br>    -- Start fresh<br>    TRUNCATE TABLE ORDERS_STG;<br>    -- Load new data into staging<br>    COPY INTO ORDERS_STG FROM (<br>        SELECT $1, $2, $3, $4, $5, METADATA$FILENAME, CURRENT_TIMESTAMP<br>        FROM @ORDERS_STAGE<br>    )<br>    FILE_FORMAT = (TYPE=CSV, SKIP_HEADER=1)<br>    ON_ERROR = ABORT_STATEMENT<br>    PURGE = TRUE;    <br>-- Merge staged data into the target table<br>    MERGE INTO CUSTOMER_ORDERS TGT <br>    USING ORDERS_STG AS SRC<br>    ON  <br>        SRC.CUSTOMER = TGT.CUSTOMER<br>        AND SRC.DELIVERY_DATE = TGT.DELIVERY_DATE<br>        AND SRC.ITEM_TYPE = TGT.ITEM_TYPE<br>    WHEN MATCHED THEN<br>        UPDATE SET <br>            TGT.QUANTITY = SRC.QUANTITY,<br>            TGT.SOURCE_FILE = SRC.SOURCE_FILE,<br>            TGT.LOAD_TIMESTAMP = CURRENT_TIMESTAMP()<br>    WHEN NOT MATCHED THEN <br>        INSERT (CUSTOMER, ORDER_DATE, DELIVERY_DATE, ITEM_TYPE, QUANTITY, SOURCE_FILE, LOAD_TIMESTAMP)<br>        VALUES (SRC.CUSTOMER, SRC.ORDER_DATE, SRC.DELIVERY_DATE, SRC.ITEM_TYPE, SRC.QUANTITY, SRC.SOURCE_FILE, CURRENT_TIMESTAMP());<br><br>    -- Truncate and refresh summary table<br>    TRUNCATE TABLE SUMMARY_ORDERS;<br>    INSERT INTO SUMMARY_ORDERS (DELIVERY_DATE, ITEM_TYPE, TOTAL_QUANTITY)<br>    SELECT DELIVERY_DATE, ITEM_TYPE, SUM(QUANTITY) <br>    FROM CUSTOMER_ORDERS<br>    GROUP BY DELIVERY_DATE, ITEM_TYPE;<br>END;</pre><h4>Enabling and Executing the Task</h4><p>By default, tasks are created in a <strong>suspended state</strong>. To activate it:</p><pre>USE ROLE ACCOUNTADMIN;<br>GRANT EXECUTE TASK ON ACCOUNT TO ROLE SYSADMIN;<br>USE ROLE SYSADMIN;<br>EXECUTE TASK SUMMARIZE_ORDERS;</pre><p>To check the <strong>task execution history</strong>, run:</p><pre>SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY()) ORDER BY SCHEDULED_TIME DESC;</pre><p>To <strong>stop the task</strong> if needed:</p><pre>ALTER TASK SUMMARIZE_ORDERS SUSPEND;</pre><p>This ensures that data ingestion, transformation, and summarization happen <strong>automatically</strong> without manual intervention.</p><h3>Final Thoughts</h3><p>This structured approach provides a <strong>complete data pipeline in Snowflake</strong>:</p><ol><li><strong>Ingesting raw data using stages</strong></li><li><strong>Loading it into a structured staging table</strong></li><li><strong>Merging updates into t</strong>This setup ensures data integrity, efficient processing, and minimal manual effort.<strong>he final table</strong></li><li><strong>Summarizing data for reporting</strong></li><li><strong>Automating the entire workflow with Snowflake Tasks</strong></li></ol><p>Enabling and Executing the Task By following this approach, I gained a solid understanding of <strong>Snowflake’s object model, data ingestion methods, and automation capabilities</strong>, helping me build a foundation for more advanced data engineering workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a8d0c95406" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>