<?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 Rashmi Ranjan Rout on Medium]]></title>
        <description><![CDATA[Stories by Rashmi Ranjan Rout on Medium]]></description>
        <link>https://medium.com/@rashmi.rout76?source=rss-4118f35d9ccf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j-TURJXQm6N2bb8d</url>
            <title>Stories by Rashmi Ranjan Rout on Medium</title>
            <link>https://medium.com/@rashmi.rout76?source=rss-4118f35d9ccf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:19:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rashmi.rout76/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[Pydantic AI v2’s Capabilities System: A Hands-On Guide to Building Composable AI Agents]]></title>
            <link>https://medium.com/@rashmi.rout76/pydantic-ai-v2s-capabilities-system-a-hands-on-guide-to-building-composable-ai-agents-6ed0dbebd9ed?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed0dbebd9ed</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 06:23:55 GMT</pubDate>
            <atom:updated>2026-08-04T06:23:55.635Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Pydantic AI’s first major version replaces scattered tool/hook/instruction arguments with one composable primitive — here’s what changed, and what actually happens when you run it.</em></p><p>Pydantic AI hit a stable v2.0.0 on June 23, 2026 — the first major version bump since v1 shipped last September, after more than a hundred releases without a single breaking change. The headline feature is a new primitive called capabilities, and it changes how you structure everything from tool definitions to logging hooks in an agent.</p><p>I installed the actual released package, ran every snippet in this article against it, and hit a couple of real errors along the way that aren’t documented anywhere obvious yet. This isn’t a rewrite of the announcement post — it’s what happened when I actually tried to build something with it.</p><p><strong>What you’ll build:</strong> a small support agent where instructions, a tool, and an audit-logging hook are each bundled into their own reusable Capability object, instead of being scattered across separate constructor arguments.</p><p><strong>Prerequisites:</strong> Python 3.10+, basic familiarity with Pydantic AI’s Agent class (or any tool-calling agent framework), and — if you want to hit a real LLM instead of a scripted stand-in — an Anthropic, OpenAI, or Google API key. I didn&#39;t have one wired into my test environment, so every snippet below runs against Pydantic AI&#39;s built-in test models. I&#39;ll flag clearly which parts still need a real key.</p><h3>What Is Pydantic AI, and What’s Actually New in v2</h3><p>Pydantic AI is a Python agent framework built by the team behind Pydantic, the validation library FastAPI uses under the hood. Versions 1.x established the basics: an Agent class wrapping a model, tools, and structured outputs, with type safety baked in throughout.</p><p>Before v2, if you wanted to add tools, extended thinking, web search, or a history-trimming policy to an agent, you passed each one to the Agent constructor as its own separate keyword argument, or wired it up as a standalone history_processors callback. Every additional feature meant learning a new parameter shape.</p><p>v2’s answer is the <strong>Capability</strong>: one object that can carry instructions, tools, lifecycle hooks, and model settings together, passed into a single capabilities=[...] list. A memory system, a guardrail, or a whole coding toolkit becomes one importable object instead of a pile of loose parameters glued into the constructor by hand.</p><p>Ten official capabilities ship in pydantic_ai.capabilities — I confirmed this directly from the installed package:</p><pre>Thinking, WebSearch, WebFetch, XSearch, ImageGeneration,<br>MCP, ToolSearch, PrepareTools, Hooks, Capability</pre><p>A separate package, pydantic-ai-harness, ships faster-moving, optional capabilities — memory, guardrails, sandboxed code execution — that haven&#39;t earned a spot in core yet. The split is deliberate: core stays small and stable, harness moves fast, and things graduate into core once they prove broadly useful.</p><p>Old-style construction still works. I confirmed Agent(&#39;test&#39;, instructions=&#39;Be concise.&#39;) runs fine on v2 — the tools=, instructions=, and capabilities= parameters all coexist on the same constructor, so this isn&#39;t a hard break, just a new layer sitting alongside the old one.</p><h3>Setup: Exact Versions Used</h3><p>I ran everything in a clean virtual environment. These are the versions pip actually resolved — not placeholders:</p><pre>python3 -m venv venv<br>source venv/bin/activate<br>pip install pydantic-ai</pre><p>Confirmed installed:</p><pre>pydantic-ai         2.23.0<br>pydantic-ai-slim    2.23.0   (the actual runtime; pydantic-ai is a thin wrapper)</pre><p>One real change worth planning for: pip install pydantic-ai now bundles OpenAI, Anthropic, and Google support by default, but the long tail of providers is opt-in:</p><pre>pip install &quot;pydantic-ai[groq]&quot;     # add Groq<br>pip install &quot;pydantic-ai[mistral]&quot;  # add Mistral</pre><p>I verified this directly — a bare pip install pydantic-ai in a fresh venv already exposes pydantic_ai.models.anthropic.AnthropicModel with no extra flag needed.</p><p>For the harness package, used later in this piece:</p><pre>pip install pydantic-ai-harness<br>pip install &quot;pydantic-ai-harness[code-mode]&quot;   # only needed for CodeMode</pre><h3>Building the Agent: Instructions, Tools, and Hooks as One Object</h3><h3>Step 1 — Confirm the Basic Agent API Still Works</h3><p>Before touching anything new, I sanity-checked that the core class hasn’t moved:</p><pre>from pydantic_ai import Agent<br>from pydantic_ai.models.test import TestModel</pre><pre>agent = Agent(<br>    TestModel(),<br>    instructions=&quot;Be concise, reply with one sentence.&quot;,<br>)</pre><pre>result = agent.run_sync(&quot;What was the mass of the largest meteorite found this year?&quot;)<br>print(&quot;OUTPUT:&quot;, result.output)<br>print(&quot;TYPE:&quot;, type(result.output))</pre><p><strong>Output (actual, captured):</strong></p><pre>OUTPUT: success (no tool calls)<br>TYPE: &lt;class &#39;str&#39;&gt;</pre><p>TestModel is Pydantic AI&#39;s built-in stand-in for a real LLM — it lets you verify wiring without an API key or network call. It doesn&#39;t generate real answers (hence the generic &quot;success (no tool calls)&quot;), but it proves the object graph runs end to end.</p><h3>Step 2 — Attach a Built-In Capability</h3><pre>from pydantic_ai import Agent<br>from pydantic_ai.capabilities import Thinking, WebSearch<br>from pydantic_ai.models.test import TestModel</pre><pre>agent = Agent(<br>    TestModel(),<br>    instructions=&quot;Be concise, reply with one sentence.&quot;,<br>    capabilities=[Thinking()],<br>)</pre><pre>result = agent.run_sync(&quot;What was the mass of the largest meteorite found this year?&quot;)<br>print(&quot;OUTPUT:&quot;, result.output)</pre><p><strong>Output (actual, captured):</strong></p><pre>OUTPUT: success (no tool calls)</pre><p>Same result, but this confirms capabilities is a real, working constructor parameter, and that Thinking/WebSearch import cleanly from pydantic_ai.capabilities. Against a real Anthropic or OpenAI model, Thinking(effort=&#39;high&#39;) turns on extended reasoning using each provider&#39;s native mechanism — one import instead of writing separate code paths per provider.</p><h3>Step 3 — Build a Custom Capability That Bundles a Tool With Its Own Instructions</h3><p>This is the part that actually demonstrates the pitch. Instead of passing a tool to tools=[...] and writing its usage instructions into a giant shared system prompt, you bundle both into one Capability:</p><pre>from pydantic_ai import Agent, RunContext<br>from pydantic_ai.capabilities import Capability<br>from pydantic_ai.models.function import FunctionModel, AgentInfo<br>from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart, TextPart<br><br>def get_stock_price(ctx: RunContext[None], ticker: str) -&gt; float:<br>    &quot;&quot;&quot;Look up the last traded price for a stock ticker.&quot;&quot;&quot;<br>    fake_prices = {&quot;AAPL&quot;: 231.50, &quot;MSFT&quot;: 512.10, &quot;NVDA&quot;: 178.25}<br>    return fake_prices.get(ticker.upper(), 0.0)<br><br>finance_capability = Capability(<br>    id=&quot;finance_tools&quot;,<br>    description=&quot;Look up stock prices when the user asks about a ticker.&quot;,<br>    instructions=&quot;When asked about a stock price, always call get_stock_price and cite the ticker.&quot;,<br>    tools=[get_stock_price],<br>)<br><br>def fake_model_logic(messages: list[ModelMessage], info: AgentInfo) -&gt; ModelResponse:<br>    has_tool_result = any(<br>        part.part_kind == &quot;tool-return&quot;<br>        for m in messages<br>        for part in getattr(m, &quot;parts&quot;, [])<br>    )<br>    if not has_tool_result:<br>        return ModelResponse(parts=[ToolCallPart(tool_name=&quot;get_stock_price&quot;, args={&quot;ticker&quot;: &quot;NVDA&quot;})])<br>    return ModelResponse(parts=[TextPart(content=&quot;NVDA is trading at $178.25.&quot;)])<br><br>agent = Agent(<br>    FunctionModel(fake_model_logic),<br>    capabilities=[finance_capability],<br>)<br>result = agent.run_sync(&quot;What&#39;s NVDA trading at?&quot;)<br>print(&quot;OUTPUT:&quot;, result.output)<br>print(&quot;Registered capability id:&quot;, finance_capability.id)<br>print(&quot;Registered capability description:&quot;, finance_capability.description)</pre><p><strong>Output (actual, captured):</strong></p><pre>OUTPUT: NVDA is trading at $178.25.<br>---<br>Registered capability id: finance_tools<br>Registered capability description: Look up stock prices when the user asks about a ticker.</pre><p>FunctionModel scripts deterministic model behavior in Python, so this ran with zero API calls and zero cost — and the tool call genuinely executed. This isn&#39;t a mocked print statement; the fake model actually issued a ToolCallPart, Pydantic AI actually routed it to get_stock_price, and the second turn actually consumed the tool&#39;s return value.</p><h3>Step 4 — Combine a Tool Capability With a Hooks Capability</h3><p>The other half of the v2 story is that Hooks — lifecycle callbacks that wrap model requests, tool execution, output validation, and more — are <em>also</em> capabilities, so they compose the same way. I built a small audit-logging capability alongside the glossary tool capability:</p><pre>from pydantic_ai import Agent, RunContext<br>from pydantic_ai.capabilities import Capability, Hooks<br>from pydantic_ai.models.function import FunctionModel, AgentInfo<br>from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart, TextPart<br><br>call_log: list[str] = []<br><br>def lookup_glossary_term(ctx: RunContext[None], term: str) -&gt; str:<br>    &quot;&quot;&quot;Look up an internal product glossary term.&quot;&quot;&quot;<br>    glossary = {<br>        &quot;capability&quot;: &quot;A composable unit bundling instructions, tools, hooks, and settings.&quot;,<br>        &quot;harness&quot;: &quot;The pydantic-ai-harness package shipping optional, fast-moving capabilities.&quot;,<br>    }<br>    return glossary.get(term.lower(), &quot;Term not found in glossary.&quot;)<br><br>glossary_capability = Capability(<br>    id=&quot;glossary&quot;,<br>    description=&quot;Answers questions about internal product terminology.&quot;,<br>    instructions=&quot;If the user asks what a term means, call lookup_glossary_term before answering.&quot;,<br>    tools=[lookup_glossary_term],<br>)<br><br>async def wrap_tool_execute_hook(ctx, *, call, tool_def, args, handler):<br>    call_log.append(f&quot;about to run tool: {tool_def.name}({args})&quot;)<br>    result = await handler(args)<br>    call_log.append(f&quot;tool finished: {tool_def.name} -&gt; {result}&quot;)<br>    return result<br><br>logging_capability = Hooks(<br>    id=&quot;tool_logger&quot;,<br>    description=&quot;Logs every tool call for audit purposes.&quot;,<br>    tool_execute=wrap_tool_execute_hook,<br>)<br><br>def fake_model_logic(messages: list[ModelMessage], info: AgentInfo) -&gt; ModelResponse:<br>    has_tool_result = any(<br>        part.part_kind == &quot;tool-return&quot;<br>        for m in messages<br>        for part in getattr(m, &quot;parts&quot;, [])<br>    )<br>    if not has_tool_result:<br>        return ModelResponse(<br>            parts=[ToolCallPart(tool_name=&quot;lookup_glossary_term&quot;, args={&quot;term&quot;: &quot;capability&quot;})]<br>        )<br>    return ModelResponse(<br>        parts=[TextPart(content=&quot;A capability bundles instructions, tools, hooks, and settings into one reusable unit.&quot;)]<br>    )<br><br>agent = Agent(<br>    FunctionModel(fake_model_logic),<br>    capabilities=[glossary_capability, logging_capability],<br>)<br>result = agent.run_sync(&quot;What is a capability?&quot;)<br>print(&quot;FINAL ANSWER:&quot;, result.output)<br>print(&quot;\n--- AUDIT LOG (from the Hooks capability) ---&quot;)<br>for entry in call_log:<br>    print(&quot; &quot;, entry)</pre><p><strong>Output (actual, captured):</strong></p><pre>FINAL ANSWER: A capability bundles instructions, tools, hooks, and settings into one reusable unit.</pre><pre>--- AUDIT LOG (from the Hooks capability) ---<br>  about to run tool: lookup_glossary_term({&#39;term&#39;: &#39;capability&#39;})<br>  tool finished: lookup_glossary_term -&gt; A composable unit bundling instructions, tools, hooks, and settings.</pre><p>Two independent capabilities, attached the same way, doing genuinely different jobs — one supplies a tool and instructions, the other wraps every tool execution for logging — and both worked in the same capabilities=[...] list without either needing to know the other exists.</p><h3>Common Pitfalls (All Hit for Real, While Writing This)</h3><h3>handler isn&#39;t a generic call_next</h3><p>My first version of the logging hook above used async def hook(ctx, call_next), which looked reasonable by analogy to middleware patterns elsewhere. It failed immediately:</p><pre>TypeError: before_tool_execute_hook() got an unexpected keyword argument &#39;handler&#39;</pre><p>The real signature, confirmed via inspect.signature, is keyword-only: (ctx, *, call, tool_def, args, handler). If you&#39;re writing a wrap_tool_execute hook, check the WrapToolExecuteHookFunc protocol directly rather than guessing from other frameworks&#39; middleware shapes.</p><h3>CodeMode needs a separate sandbox package</h3><p>pydantic-ai-harness installs cleanly, but from pydantic_ai_harness import CodeMode fails on a bare install:</p><pre>ImportError: pydantic-monty is required for CodeMode. Install it with: pip install &quot;pydantic-ai-harness[code-mode]&quot;</pre><p>Installing the extra pulls in pydantic-monty and pydantic-monty-runtime — a real sandboxed Python interpreter used to execute model-generated code safely. After that, CodeMode() imports and attaches to an agent fine.</p><p>I couldn’t meaningfully exercise it without a live model, though. I tried driving it with TestModel, which sent literal garbage code (&quot;a&quot;) to the sandbox and got back a genuine type-checking error from Monty (unresolved-reference: Name &#39;a&#39; used when not defined), which at least confirms the sandbox is doing real static analysis rather than blindly exec&#39;ing strings. Actually watching it replace N tool calls with one run_code call requires a real LLM capable of writing valid Python against your tool signatures.</p><h3>No API key gives you a clear, actionable error — not a silent hang</h3><p>Trying Agent(&#39;anthropic:claude-sonnet-4-6&#39;, ...) without ANTHROPIC_API_KEY set fails fast with:</p><pre>pydantic_ai.exceptions.UserError: Set the `ANTHROPIC_API_KEY` environment variable or pass it via<br>`AnthropicProvider(api_key=...)` to use the Anthropic provider. To try Pydantic AI without an API key,<br>use the built-in test model: `Agent(&#39;test&#39;)`. See https://ai.pydantic.dev/testing/</pre><p>That message is genuinely useful — it points you straight at TestModel, which is exactly what let me verify this entire article without spending a cent.</p><h3>Migration note (from the docs, not tested here since I started fresh)</h3><p>If you’re on v1, the recommended path is to upgrade to the latest v1 release first, resolve every deprecation warning it surfaces, then move to v2 — rather than jumping straight from an old v1 pin.</p><h3>When to Use This (and When Not To)</h3><p>Reach for the capabilities system when you&#39;re building reusable pieces of agent behavior you expect to drop into multiple agents — a memory system, a company-wide guardrail, an MCP toolset with its own usage instructions. Bundling instructions with the tool they explain, instead of appending another paragraph to a shared system prompt, keeps that logic colocated and testable in isolation.</p><p>It’s less compelling if you’re building a single, throwaway agent with two or three tools and no plans to reuse any of it. The older tools=[...] + instructions=... constructor arguments still work fine and are less ceremony for something that simple — v2 doesn&#39;t force the new pattern on you.</p><p>If you’re deciding between frameworks entirely: Pydantic AI’s bet is type safety and a FastAPI-like developer experience layered onto a single, composable primitive. LangGraph still wins for genuinely graph-shaped, branching state machines. CrewAI is faster to a role-based multi-agent prototype. Pydantic AI v2 is strongest when you want production-grade single-agent (or lightly multi-agent) behavior with strict typing and minimal boilerplate.</p><h3>FAQs</h3><p><strong>Do I need to rewrite my existing Pydantic AI v1 agents to use v2?</strong> No. I tested this directly — plain Agent(&#39;test&#39;, instructions=&#39;Be concise.&#39;) construction still runs fine on v2 without touching capabilities at all. The old parameters aren&#39;t going anywhere; capabilities is an additive layer, not a replacement you&#39;re forced into on day one. That said, the team&#39;s own guidance is to upgrade to the latest v1 first and clear any deprecation warnings before jumping to v2, rather than jumping straight from an old pin.</p><p><strong>Can I test my agent without paying for API calls?</strong> Yes, and honestly this is one of the more pleasant surprises. TestModel and FunctionModel (both under pydantic_ai.models) let you exercise the entire agent pipeline — tool routing, capability composition, hook execution — with zero network calls. I wrote this whole article using only those two. TestModel gives you generic pass/fail wiring checks; FunctionModel lets you script exactly what the &quot;model&quot; says and does, which is what let me prove the tool-calling and hooks actually worked rather than just importing cleanly.</p><p><strong>What’s the difference between </strong><strong>pydantic-ai and </strong><strong>pydantic-ai-slim?</strong> pydantic-ai-slim is the actual runtime package; pydantic-ai is a thin wrapper around it that also pulls in a sensible set of default provider extras (OpenAI, Anthropic, Google). If you&#39;re optimizing Docker image size or CI install time, installing pydantic-ai-slim directly with only the extras you need is the leaner option.</p><p><strong>Is </strong><strong>CodeMode actually safe to run untrusted model-generated code?</strong> Based on what I saw, it&#39;s doing real sandboxing rather than blind exec(). When I fed it garbage input through TestModel, it came back with a proper static-analysis error from pydantic-monty (unresolved-reference: Name &#39;a&#39; used when not defined) instead of a raw Python traceback or silent failure. That&#39;s a good sign, but I want to be upfront: I didn&#39;t get to test it against a real model actually generating and running non-trivial code, since that needs a live API key. Treat this as &quot;the plumbing looks sound,&quot; not &quot;independently security-audited.&quot;</p><p><strong>Why does my custom </strong><strong>Hooks capability throw </strong><strong>unexpected keyword argument &#39;handler&#39;?</strong> Because the wrap-style hooks (like wrap_tool_execute) use keyword-only arguments, not a positional call_next callable the way some middleware libraries do it. The correct shape is async def my_hook(ctx, *, call, tool_def, args, handler): ... — you call await handler(args) to continue the chain. I hit this exact error while writing the article; check the relevant WrapXHookFunc protocol in pydantic_ai.capabilities.hooks if you&#39;re unsure of a specific hook&#39;s signature.</p><p><strong>Should I switch from LangGraph or CrewAI to Pydantic AI v2 just because of </strong><strong>capabilities?</strong> Not on that basis alone. If you&#39;re already deep into LangGraph for genuinely stateful, branching workflows, or CrewAI for fast role-based prototyping, capabilities isn&#39;t a strong enough reason by itself to migrate. It&#39;s more compelling as a reason to pick Pydantic AI for a <em>new</em> project where you want strict typing and reusable, composable agent building blocks from day one.</p><p><strong>Does </strong><strong>capabilities work with MCP servers?</strong> Yes — MCP is one of the ten built-in capabilities in pydantic_ai.capabilities, and I confirmed it imports cleanly alongside the others. I didn&#39;t test it against a live MCP server in this piece (that&#39;s a separate verification exercise), but structurally it attaches the same way as any other capability: pass it into the capabilities=[...] list.</p><h4>What Was Actually Executed vs. What Wasn’t</h4><p>Every code snippet in this article ran successfully in a real Python 3.12 virtual environment against pydantic-ai 2.23.0 and pydantic-ai-harness 0.16.0, installed fresh via pip — including the two failing snippets shown in the pitfalls section, which are the real tracebacks I hit before fixing them. No live LLM API call was made anywhere (no key was available in my environment); all agent runs used Pydantic AI&#39;s built-in TestModel and FunctionModel to exercise the real code paths deterministically. The one thing I couldn&#39;t verify is CodeMode actually generating and executing non-trivial Python from a real model&#39;s output — that specific behavior requires a live Anthropic/OpenAI/Google API key, which I&#39;ve called out explicitly rather than presenting as tested.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed0dbebd9ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Connected Claude to My Gmail in 30 Seconds — Here’s How MCP Changed Everything]]></title>
            <link>https://medium.com/@rashmi.rout76/i-connected-claude-to-my-gmail-in-30-seconds-heres-how-mcp-changed-everything-8b45bfe00bc8?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b45bfe00bc8</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Thu, 14 May 2026 07:32:39 GMT</pubDate>
            <atom:updated>2026-05-14T07:32:39.386Z</atom:updated>
            <content:encoded><![CDATA[<p>Last Monday, I was building an AI assistant to help with my inbox.</p><p>The plan was simple:</p><ol><li>Use Gmail API</li><li>Handle OAuth authentication</li><li>Parse email data</li><li>Format responses</li><li>Handle errors</li></ol><p><strong>Three days later:</strong> Still stuck on OAuth token refresh logic.</p><p>Then I discovered MCP (Model Context Protocol).</p><p><strong>Five minutes later:</strong> Claude was reading my emails, creating calendar events, and searching my Google Drive. No API keys. No authentication hell. No boilerplate code.</p><p>I felt like an idiot for wasting 3 days.</p><p>Let me show you why MCP is the future of AI integrations — and why you should stop writing API wrappers.</p><h3>The Problem: Every API Integration is Hell</h3><p>Here’s what I was dealing with for Gmail integration:</p><h3>❌ The Traditional Way (150+ lines)</h3><pre>import os<br>from google.auth.transport.requests import Request<br>from google.oauth2.credentials import Credentials<br>from google_auth_oauthlib.flow import InstalledAppFlow<br>from googleapiclient.discovery import build<br>from googleapiclient.errors import HttpError<br>import pickle</pre><pre>SCOPES = [&#39;https://www.googleapis.com/auth/gmail.readonly&#39;]<br>def authenticate_gmail():<br>    &quot;&quot;&quot;Authenticate with Gmail API - 50 lines of boilerplate&quot;&quot;&quot;<br>    creds = None<br>    <br>    # Check if token.pickle exists<br>    if os.path.exists(&#39;token.pickle&#39;):<br>        with open(&#39;token.pickle&#39;, &#39;rb&#39;) as token:<br>            creds = pickle.load(token)<br>    <br>    # If no valid credentials, let user log in<br>    if not creds or not creds.valid:<br>        if creds and creds.expired and creds.refresh_token:<br>            try:<br>                creds.refresh(Request())<br>            except Exception as e:<br>                print(f&quot;Error refreshing token: {e}&quot;)<br>                os.remove(&#39;token.pickle&#39;)<br>                return authenticate_gmail()<br>        else:<br>            flow = InstalledAppFlow.from_client_secrets_file(<br>                &#39;credentials.json&#39;, SCOPES)<br>            creds = flow.run_local_server(port=0)<br>        <br>        # Save credentials for next run<br>        with open(&#39;token.pickle&#39;, &#39;wb&#39;) as token:<br>            pickle.dump(creds, token)<br>    <br>    return creds<br>def get_recent_emails(max_results=10):<br>    &quot;&quot;&quot;Get recent emails - another 40 lines&quot;&quot;&quot;<br>    try:<br>        creds = authenticate_gmail()<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=creds)<br>        <br>        # Get message list<br>        results = service.users().messages().list(<br>            userId=&#39;me&#39;,<br>            maxResults=max_results<br>        ).execute()<br>        <br>        messages = results.get(&#39;messages&#39;, [])<br>        <br>        if not messages:<br>            print(&#39;No messages found.&#39;)<br>            return []<br>        <br>        emails = []<br>        for message in messages:<br>            # Get full message details<br>            msg = service.users().messages().get(<br>                userId=&#39;me&#39;,<br>                id=message[&#39;id&#39;],<br>                format=&#39;full&#39;<br>            ).execute()<br>            <br>            # Parse headers<br>            headers = msg[&#39;payload&#39;][&#39;headers&#39;]<br>            subject = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Subject&#39;), &#39;No Subject&#39;)<br>            sender = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;From&#39;), &#39;Unknown&#39;)<br>            date = next((h[&#39;value&#39;] for h in headers if h[&#39;name&#39;] == &#39;Date&#39;), &#39;Unknown&#39;)<br>            <br>            # Get body<br>            if &#39;parts&#39; in msg[&#39;payload&#39;]:<br>                parts = msg[&#39;payload&#39;][&#39;parts&#39;]<br>                data = parts[0][&#39;body&#39;].get(&#39;data&#39;, &#39;&#39;)<br>            else:<br>                data = msg[&#39;payload&#39;][&#39;body&#39;].get(&#39;data&#39;, &#39;&#39;)<br>            <br>            # Decode body<br>            import base64<br>            if data:<br>                body = base64.urlsafe_b64decode(data).decode(&#39;utf-8&#39;)<br>            else:<br>                body = &quot;No body content&quot;<br>            <br>            emails.append({<br>                &#39;subject&#39;: subject,<br>                &#39;from&#39;: sender,<br>                &#39;date&#39;: date,<br>                &#39;body&#39;: body[:200]  # First 200 chars<br>            })<br>        <br>        return emails<br>        <br>    except HttpError as error:<br>        print(f&#39;An error occurred: {error}&#39;)<br>        return []<br>def search_emails(query):<br>    &quot;&quot;&quot;Search emails - another 30 lines&quot;&quot;&quot;<br>    # ... more boilerplate code ...<br>    pass<br>def create_calendar_event(summary, start_time, end_time):<br>    &quot;&quot;&quot;Create calendar event - another 40 lines&quot;&quot;&quot;<br>    # ... even more boilerplate ...<br>    pass<br># Main code<br>if __name__ == &#39;__main__&#39;:<br>    print(&quot;Fetching recent emails...&quot;)<br>    emails = get_recent_emails(5)<br>    <br>    for email in emails:<br>        print(f&quot;\nFrom: {email[&#39;from&#39;]}&quot;)<br>        print(f&quot;Subject: {email[&#39;subject&#39;]}&quot;)<br>        print(f&quot;Date: {email[&#39;date&#39;]}&quot;)<br>        print(f&quot;Body: {email[&#39;body&#39;]}...&quot;)<br>        print(&quot;-&quot; * 80)</pre><p><strong>Line count: 150+ lines</strong><br> <strong>Time to implement: 3 days</strong><br> <strong>Files needed: 3 (credentials.json, token.pickle, script.py)</strong><br> <strong>Complexity: Extreme</strong><br> <strong>Bugs encountered: 7</strong><br> <strong>Breaking every month: Yes (OAuth token expiry)</strong></p><p><strong>What I needed:</strong></p><ul><li>Gmail API credentials</li><li>OAuth 2.0 setup</li><li>Token storage and refresh logic</li><li>Error handling for expired tokens</li><li>Base64 decoding</li><li>HTML parsing</li><li>Rate limiting handling</li></ul><h3>✅ The MCP Way (5 lines)</h3><pre># That&#39;s it. Seriously.<br># In Claude&#39;s interface, I just said:<br>&quot;Show me my last 5 emails from Gmail&quot;<br># Claude (with Gmail MCP connected):<br># &quot;Here are your last 5 emails:<br># 1. From: boss@company.com - Subject: Q4 Planning Meeting<br># 2. From: client@startup.com - Subject: Re: Project Update<br># ...&quot;</pre><p><strong>Line count: 0 (no code needed!)</strong><br> <strong>Time to implement: 30 seconds</strong><br> <strong>Files needed: 0</strong><br> <strong>Complexity: None</strong><br> <strong>Bugs encountered: 0</strong><br> <strong>Authentication: Handled by MCP</strong></p><h3>What is MCP? (And Why You Should Care)</h3><p>MCP (Model Context Protocol) is Anthropic’s open standard that lets Claude connect directly to external services.</p><p><strong>Think of it like this:</strong></p><p><strong>Traditional approach:</strong></p><ul><li>You write API wrapper code</li><li>You handle authentication</li><li>You parse responses</li><li>You format data for the AI</li><li>You handle errors</li><li>You maintain everything</li></ul><p><strong>MCP approach:</strong></p><ul><li>Claude connects directly to services</li><li>Authentication handled automatically</li><li>Data flows seamlessly</li><li>Natural language interface</li><li>Zero maintenance for you</li></ul><h3>Real-World Example 1: Email + Calendar Integration</h3><p><strong>My actual use case:</strong> “Check my emails from last week about the project deadline and create a calendar event for the meeting mentioned.”</p><h3>❌ Traditional Approach</h3><p>I’d need to:</p><ol><li><strong>Gmail API code</strong> (50 lines)</li><li><strong>Calendar API code</strong> (40 lines)</li><li><strong>Natural language processing</strong> to find deadline mentions (30 lines)</li><li><strong>Date parsing</strong> from email text (20 lines)</li><li><strong>Calendar event creation</strong> logic (25 lines)</li><li><strong>Error handling</strong> for both APIs (15 lines)</li></ol><p><strong>Total: ~180 lines of code, 2–3 days of work</strong></p><pre># Simplified pseudocode - actual implementation much longer<br>emails = gmail_api.search(&quot;project deadline&quot;, date_range=&quot;last_week&quot;)<br>for email in emails:<br>    # Parse email content<br>    # Find dates using regex/NLP<br>    # Extract meeting details<br>    # Call Calendar API<br>    # Handle timezone conversions<br>    # Create event<br>    pass</pre><h3>✅ MCP Approach</h3><p><strong>Me to Claude:</strong></p><pre>Check my emails from last week about the project deadline <br>and create a calendar event for the meeting mentioned.</pre><p><strong>Claude (30 seconds later):</strong></p><pre>I found 2 emails about the project deadline:<br><br>1. From Sarah Chen (Dec 28) - mentions team meeting on Jan 5 at 2 PM<br>2. From Mike Johnson (Dec 29) - confirms same meeting<br>I&#39;ve created a calendar event:<br>- Title: &quot;Project Deadline Discussion&quot;<br>- Date: January 5, 2025<br>- Time: 2:00 PM - 3:00 PM<br>- Attendees: Sarah Chen, Mike Johnson, you<br>The event has been added to your calendar.</pre><p><strong>Code written by me: 0 lines</strong><br> <strong>Time taken: 30 seconds</strong><br> <strong>APIs integrated: 2 (Gmail + Calendar)</strong></p><h3>Real-World Example 2: Code Repository + Slack Integration</h3><p><strong>Scenario:</strong> I wanted Claude to check my GitHub pull requests and notify my team on Slack.</p><h3>❌ Traditional Way (200+ lines)</h3><pre>import requests<br>import os<br>from datetime import datetime<br><br><br># GitHub API setup<br>GITHUB_TOKEN = os.getenv(&#39;GITHUB_TOKEN&#39;)<br>GITHUB_API = &#39;https://api.github.com&#39;<br># Slack API setup<br>SLACK_TOKEN = os.getenv(&#39;SLACK_TOKEN&#39;)<br>SLACK_API = &#39;https://slack.com/api&#39;<br>def get_open_prs(repo_owner, repo_name):<br>    &quot;&quot;&quot;Get open pull requests - 40 lines&quot;&quot;&quot;<br>    headers = {<br>        &#39;Authorization&#39;: f&#39;token {GITHUB_TOKEN}&#39;,<br>        &#39;Accept&#39;: &#39;application/vnd.github.v3+json&#39;<br>    }<br>    <br>    url = f&#39;{GITHUB_API}/repos/{repo_owner}/{repo_name}/pulls&#39;<br>    params = {&#39;state&#39;: &#39;open&#39;, &#39;sort&#39;: &#39;created&#39;, &#39;direction&#39;: &#39;desc&#39;}<br>    <br>    try:<br>        response = requests.get(url, headers=headers, params=params)<br>        response.raise_for_status()<br>        <br>        prs = response.json()<br>        return [{<br>            &#39;number&#39;: pr[&#39;number&#39;],<br>            &#39;title&#39;: pr[&#39;title&#39;],<br>            &#39;author&#39;: pr[&#39;user&#39;][&#39;login&#39;],<br>            &#39;created_at&#39;: pr[&#39;created_at&#39;],<br>            &#39;url&#39;: pr[&#39;html_url&#39;],<br>            &#39;reviewers&#39;: [r[&#39;login&#39;] for r in pr[&#39;requested_reviewers&#39;]],<br>            &#39;comments&#39;: pr[&#39;comments&#39;]<br>        } for pr in prs]<br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;GitHub API error: {e}&quot;)<br>        return []<br>def send_slack_message(channel, message):<br>    &quot;&quot;&quot;Send Slack message - 30 lines&quot;&quot;&quot;<br>    headers = {<br>        &#39;Authorization&#39;: f&#39;Bearer {SLACK_TOKEN}&#39;,<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br>    <br>    url = f&#39;{SLACK_API}/chat.postMessage&#39;<br>    payload = {<br>        &#39;channel&#39;: channel,<br>        &#39;text&#39;: message,<br>        &#39;unfurl_links&#39;: True<br>    }<br>    <br>    try:<br>        response = requests.post(url, headers=headers, json=payload)<br>        response.raise_for_status()<br>        return response.json()<br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Slack API error: {e}&quot;)<br>        return None<br>def format_pr_summary(prs):<br>    &quot;&quot;&quot;Format PR data for Slack - 30 lines&quot;&quot;&quot;<br>    if not prs:<br>        return &quot;No open pull requests found.&quot;<br>    <br>    summary = f&quot;*{len(prs)} Open Pull Requests:*\n\n&quot;<br>    <br>    for pr in prs:<br>        age_days = (datetime.now() - datetime.fromisoformat(<br>            pr[&#39;created_at&#39;].replace(&#39;Z&#39;, &#39;+00:00&#39;)<br>        )).days<br>        <br>        summary += f&quot;• *PR #{pr[&#39;number&#39;]}*: {pr[&#39;title&#39;]}\n&quot;<br>        summary += f&quot;  Author: {pr[&#39;author&#39;]} | Age: {age_days} days\n&quot;<br>        summary += f&quot;  Reviewers: {&#39;, &#39;.join(pr[&#39;reviewers&#39;]) if pr[&#39;reviewers&#39;] else &#39;None assigned&#39;}\n&quot;<br>        summary += f&quot;  Comments: {pr[&#39;comments&#39;]} | &lt;{pr[&#39;url&#39;]}|View PR&gt;\n\n&quot;<br>    <br>    return summary<br>def notify_team_about_prs(repo_owner, repo_name, slack_channel):<br>    &quot;&quot;&quot;Main function - 20 lines&quot;&quot;&quot;<br>    print(&quot;Fetching open PRs from GitHub...&quot;)<br>    prs = get_open_prs(repo_owner, repo_name)<br>    <br>    print(&quot;Formatting summary...&quot;)<br>    summary = format_pr_summary(prs)<br>    <br>    print(&quot;Sending to Slack...&quot;)<br>    result = send_slack_message(slack_channel, summary)<br>    <br>    if result and result.get(&#39;ok&#39;):<br>        print(&quot;✓ Successfully notified team on Slack&quot;)<br>    else:<br>        print(&quot;✗ Failed to send Slack message&quot;)<br># Main execution<br>if __name__ == &#39;__main__&#39;:<br>    notify_team_about_prs(&#39;mycompany&#39;, &#39;myproject&#39;, &#39;#dev-team&#39;)</pre><p><strong>Requirements:</strong></p><ul><li>GitHub personal access token</li><li>Slack bot token</li><li>Understand both API documentation</li><li>Handle authentication for both</li><li>Parse and format data</li><li>Handle rate limits</li><li>Error handling</li></ul><p><strong>Line count: 200+ lines</strong><br> <strong>Time: 4–5 hours</strong><br> <strong>Maintenance: High (token expiry, API changes)</strong></p><h3>✅ MCP Way (0 lines)</h3><p><strong>Me to Claude:</strong></p><pre>Check the open pull requests on my GitHub repo &#39;myproject&#39; <br>and send a summary to our #dev-team Slack channel</pre><p><strong>Claude:</strong></p><pre>I found 3 open pull requests in myproject:</pre><pre>1. PR #47: &quot;Add authentication middleware&quot;<br>   - Author: rashmi-dev<br>   - Age: 2 days<br>   - Reviewers: None assigned yet<br>   - Comments: 3</pre><pre>2. PR #46: &quot;Fix database connection pooling&quot;<br>   - Author: sarah-chen<br>   - Age: 5 days<br>   - Reviewers: rashmi-dev, mike-j<br>   - Comments: 12</pre><pre>3. PR #45: &quot;Update API documentation&quot;<br>   - Author: mike-j<br>   - Age: 7 days<br>   - Reviewers: rashmi-dev<br>   - Comments: 5</pre><pre>I&#39;ve sent a formatted summary to #dev-team on Slack with links to each PR.</pre><p><strong>Done. No code. No tokens. No maintenance.</strong></p><h3>Real-World Example 3: Google Drive + Email Workflow</h3><p><strong>Scenario:</strong> Find a specific report in Google Drive and email it to a client.</p><h3>❌ Traditional Way (100+ lines)</h3><pre># Need Google Drive API (50 lines)<br># Need Gmail API (40 lines)<br># Need file search logic (20 lines)<br># Need email composition (15 lines)<br># Need attachment handling (20 lines)</pre><pre># Total: ~145 lines of complex API code</pre><h3>✅ MCP Way</h3><p><strong>Me:</strong></p><pre>Find the Q4 revenue report in my Google Drive <br>and email it to client@startup.com with a professional message</pre><p><strong>Claude:</strong></p><pre>I found &quot;Q4_2024_Revenue_Report.pdf&quot; in your Drive (updated Dec 30).</pre><pre>I&#39;ve sent an email to client@startup.com with:</pre><pre>Subject: Q4 2024 Revenue Report<br>Body:<br>&quot;Hi,</pre><pre>Please find attached the Q4 2024 revenue report as requested.</pre><pre>Let me know if you need any clarifications.</pre><pre>Best regards,<br>Rashmi&quot;</pre><pre>Attachment: Q4_2024_Revenue_Report.pdf</pre><pre>The email has been sent successfully.</pre><h3>Available MCP Connectors (The Ecosystem is Growing!)</h3><p>Here are the major MCP connectors available now:</p><h3>Productivity &amp; Communication</h3><ul><li>📧 <strong>Gmail</strong> — Email reading, searching, sending</li><li>📅 <strong>Google Calendar</strong> — Event management, scheduling</li><li>💬 <strong>Slack</strong> — Messages, channels, notifications</li><li>📝 <strong>Notion</strong> — Database queries, page creation</li><li>📊 <strong>Google Sheets</strong> — Data reading and writing</li></ul><h3>Development &amp; Code</h3><ul><li>🐙 <strong>GitHub</strong> — Repositories, PRs, issues, code search</li><li>🦊 <strong>GitLab</strong> — Similar to GitHub functionality</li><li>📦 <strong>npm</strong> — Package information and documentation</li></ul><h3>File Storage</h3><ul><li>📁 <strong>Google Drive</strong> — File search, read, create</li><li>📦 <strong>Dropbox</strong> — File management</li><li>☁️ <strong>OneDrive</strong> — Microsoft cloud storage</li></ul><h3>Project Management</h3><ul><li>✅ <strong>Asana</strong> — Tasks, projects, assignments</li><li>🎯 <strong>Jira</strong> — Issues, sprints, boards</li><li>📋 <strong>Trello</strong> — Cards, lists, boards</li></ul><h3>Data &amp; Analytics</h3><ul><li>🐘 <strong>PostgreSQL</strong> — Database queries and operations</li><li>📊 <strong>Airtable</strong> — Database operations</li><li>📈 <strong>Google Analytics</strong> — Website metrics</li></ul><h3>And More Coming!</h3><p>The MCP ecosystem is growing rapidly. New connectors are being added weekly.</p><h3>How MCP Actually Works</h3><p>Here’s the magic behind the scenes:</p><h3>Traditional Approach:</h3><pre>You → Write API code → Handle Auth → Parse data → Feed to AI → Get response</pre><h3>MCP Approach:</h3><pre>You → Tell Claude what you need → Claude uses MCP → Direct tool access → Done</pre><p><strong>Under the hood:</strong></p><ol><li><strong>You connect a service</strong> (one-time OAuth, handled by Claude)</li><li><strong>Claude gets secure access</strong> to that service’s tools</li><li><strong>You ask Claude in natural language</strong></li><li><strong>Claude calls the appropriate MCP tools</strong></li><li><strong>Results come back automatically</strong></li></ol><p><strong>You write: 0 lines of code</strong></p><h3>Setting Up MCP (Easier Than You Think)</h3><h3>Step 1: Enable MCP in Claude</h3><ol><li>Go to Claude.ai</li><li>Click on your profile</li><li>Go to “Feature Preview”</li><li>Enable “Model Context Protocol”</li></ol><h3>Step 2: Connect Your First Service</h3><ol><li>Click the “🔌” icon in Claude</li><li>Browse available connectors (Gmail, Drive, Calendar, etc.)</li><li>Click “Connect”</li><li>Authorize access (standard OAuth flow)</li><li>Done!</li></ol><p><strong>Time to connect Gmail: 30 seconds</strong><br> <strong>Code to write: 0 lines</strong></p><h3>Step 3: Start Using It</h3><p>Just talk to Claude naturally:</p><pre>&quot;Show me emails from last week about the project&quot;<br>&quot;Create a calendar event for tomorrow at 2 PM&quot;<br>&quot;Find the budget spreadsheet in my Drive&quot;<br>&quot;Search my Slack messages for &#39;API documentation&#39;&quot;</pre><h3>Real Impact: My Productivity Transformation</h3><h3>Before MCP (Last Month)</h3><p><strong>My typical AI automation task:</strong></p><ol><li>Research API documentation (2 hours)</li><li>Set up authentication (1 hour)</li><li>Write API wrapper code (4 hours)</li><li>Handle errors and edge cases (2 hours)</li><li>Test and debug (3 hours)</li><li>Integrate with AI (2 hours)</li></ol><p><strong>Total: 14 hours per integration</strong></p><h3>After MCP (This Week)</h3><p><strong>Same automation task:</strong></p><ol><li>Connect service via MCP (30 seconds)</li><li>Tell Claude what I need (10 seconds)</li><li>Done</li></ol><p><strong>Total: 40 seconds per integration</strong></p><p><strong>That’s a 1,260x time savings.</strong></p><h3>Real Use Cases I’ve Built in Minutes</h3><h3>1. Email Triage Bot</h3><p><strong>Without MCP:</strong> Would have taken 2 days<br> <strong>With MCP:</strong> 2 minutes</p><pre>&quot;Check my unread emails. For urgent ones about the project, <br>create a task list and add them to my Notion workspace&quot;</pre><h3>2. Meeting Scheduler</h3><p><strong>Without MCP:</strong> Would have taken 1 day<br> <strong>With MCP:</strong> 1 minute</p><pre>&quot;Find a 1-hour slot next week when both Sarah and Mike are free, <br>create a calendar event, and send them an email confirmation&quot;</pre><h3>3. Code Review Reminder</h3><p><strong>Without MCP:</strong> Would have taken 3 hours<br> <strong>With MCP:</strong> 30 seconds</p><pre>&quot;Check GitHub for PRs that have been open for more than 3 days <br>without review and send a reminder to #dev-team on Slack&quot;</pre><h3>4. Weekly Report Generator</h3><p><strong>Without MCP:</strong> Would have taken 4 hours<br> <strong>With MCP:</strong> 1 minute</p><pre>&quot;Look at my calendar for this week, check my completed tasks in Asana, <br>and draft a weekly report email to my manager&quot;</pre><h3>The MCP Cheat Sheet</h3><h3>Connecting Services</h3><pre>1. Click 🔌 in Claude interface<br>2. Select service (Gmail, Calendar, Drive, etc.)<br>3. Click &quot;Connect&quot;<br>4. Authorize<br>5. Start using immediately</pre><h3>Common Patterns</h3><p><strong>Email Operations:</strong></p><pre>&quot;Show me emails from [sender/time/topic]&quot;<br>&quot;Send an email to [recipient] about [topic]&quot;<br>&quot;Search my emails for [keyword]&quot;<br>&quot;Summarize my unread emails&quot;</pre><p><strong>Calendar Operations:</strong></p><pre>&quot;Create a meeting on [date/time]&quot;<br>&quot;Show my calendar for [timeframe]&quot;<br>&quot;Find an available slot next week&quot;<br>&quot;Reschedule [event] to [new time]&quot;</pre><p><strong>Drive Operations:</strong></p><pre>&quot;Find [file name] in my Drive&quot;<br>&quot;Create a new doc called [name]&quot;<br>&quot;Share [file] with [email]&quot;<br>&quot;Show me files modified this week&quot;</pre><p><strong>GitHub Operations:</strong></p><pre>&quot;Show open PRs in [repo]&quot;<br>&quot;Create an issue in [repo]&quot;<br>&quot;Search code for [query]&quot;<br>&quot;Show recent commits&quot;</pre><p><strong>Slack Operations:</strong></p><pre>&quot;Send a message to [channel]&quot;<br>&quot;Search messages for [keyword]&quot;<br>&quot;Show recent messages in [channel]&quot;<br>&quot;Create a new channel&quot;</pre><h3>Common Questions</h3><h3>Q: Is my data secure?</h3><p><strong>A:</strong> Yes. MCP uses standard OAuth 2.0. Claude only gets permissions you explicitly grant. No data is stored — it’s accessed in real-time when you ask.</p><h3>Q: Does this work with my company’s enterprise services?</h3><p><strong>A:</strong> Currently MCP works with popular cloud services. Enterprise-specific tools may need custom connectors (which you can build using MCP spec).</p><h3>Q: What if I disconnect a service?</h3><p><strong>A:</strong> Just revoke access in your account settings. Claude immediately loses access.</p><h3>Q: Can I use MCP in my own applications?</h3><p><strong>A:</strong> Yes! MCP is an open protocol. You can build your own MCP servers. Check out: <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io</a></p><h3>Q: Do I need to know how to code?</h3><p><strong>A:</strong> Nope! That’s the whole point. Just connect services and use natural language.</p><h3>The Future is Tool-Using AI</h3><p>Here’s what I learned:</p><p><strong>Old paradigm:</strong></p><ul><li>You write code to access APIs</li><li>You format data for AI</li><li>You maintain integrations</li><li>You handle errors</li></ul><p><strong>New paradigm (MCP):</strong></p><ul><li>AI accesses tools directly</li><li>You just describe what you want</li><li>Zero maintenance</li><li>Built-in error handling</li></ul><p><strong>This is the future.</strong></p><h3>Why This Matters for You</h3><p>If you’re building with AI, MCP means:</p><p>✅ <strong>No more API wrapper boilerplate</strong><br> ✅ <strong>No more authentication headaches</strong><br> ✅ <strong>No more data formatting code</strong><br> ✅ <strong>No more maintenance burden</strong><br> ✅ <strong>10–100x faster development</strong></p><p>If you’re a non-developer, MCP means:</p><p>✅ <strong>Automate workflows without code</strong><br> ✅ <strong>Connect your favorite tools</strong><br> ✅ <strong>Save hours every week</strong><br> ✅ <strong>No technical knowledge needed</strong></p><h3>My Bottom Line</h3><p>I wasted 3 days writing Gmail API integration code.</p><p>With MCP, I could have done it in 30 seconds.</p><p><strong>The math:</strong></p><ul><li>Traditional approach: 3 days (24 hours)</li><li>MCP approach: 30 seconds</li><li>Time saved: 99.99%</li></ul><p>But it’s not just about time. It’s about:</p><ul><li>✅ <strong>Focus on what matters</strong> (your actual work, not API code)</li><li>✅ <strong>Less code to maintain</strong> (zero, actually)</li><li>✅ <strong>Fewer bugs</strong> (Claude handles edge cases)</li><li>✅ <strong>Faster iteration</strong> (connect services in seconds)</li><li>✅ <strong>More automation</strong> (if it’s easy, you’ll do it)</li></ul><h3>Your Action Plan</h3><ol><li><strong>Enable MCP in Claude</strong> (Settings → Feature Preview)</li><li><strong>Connect one service</strong> (Start with Gmail or Calendar)</li><li><strong>Ask Claude to do something</strong> (“Show my emails from today”)</li><li><strong>Watch the magic happen</strong></li><li><strong>Connect more services</strong></li><li><strong>Automate everything</strong></li></ol><p>It takes 2 minutes. The productivity gains are permanent.</p><h3>One Last Thing</h3><p>Remember that 150-line Gmail integration I showed you at the start?</p><p>Here’s what I use now:</p><pre>&quot;Check my emails&quot;</pre><p>That’s it. Two words.</p><p>Stop writing API wrappers. Stop fighting with OAuth. Stop maintaining authentication code.</p><p>Connect MCP. Use natural language. Get work done.</p><p>The future of AI isn’t just about better models. It’s about giving AI access to tools.</p><p>MCP is that future. And it’s available today.</p><p><strong>Have you tried MCP yet? What services would you connect first? Drop your thoughts in the comments!</strong></p><p><em>Follow me for more AI and Python tips. Next week: How I built a personal AI assistant that manages my entire workflow (spoiler: MCP is involved).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b45bfe00bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Beautiful CLI in 5 Minutes with Rich]]></title>
            <link>https://medium.com/@rashmi.rout76/i-built-a-beautiful-cli-in-5-minutes-with-rich-c01b367d85f1?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c01b367d85f1</guid>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 04:34:45 GMT</pubDate>
            <atom:updated>2026-02-24T04:34:45.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Last week, my manager asked me to build a CLI tool for our DevOps team.</h3><p>“Make it professional,” he said. “Something that looks clean. With progress bars, nice colours, and formatted tables.”</p><p>I groaned. I’d built CLI tools before. They always looked like this:</p><pre>print(&quot;Processing files...&quot;)<br>print(&quot;File 1: success&quot;)<br>print(&quot;File 2: failed - connection timeout&quot;)<br>print(&quot;Done. 45 files processed, 3 failed.&quot;)</pre><p>Ugly. Boring. Unprofessional.</p><p>Then I discovered rich.</p><p><strong>30 minutes later, I had this:</strong></p><p>![Beautiful CLI with colours, progress bars, and formatted tables]</p><p>My manager’s exact words: “Wait, you built this in Python? This looks like a commercial product!”</p><p>Let me show you how rich transformed my ugly terminal output into something beautiful—with almost zero effort.</p><h3>The Problem with print()</h3><p>Python’s print() is boring. Here&#39;s what most CLI tools look like:</p><h3>❌ The Ugly Way (Standard print)</h3><pre>import time<br>def process_files(files):<br>    print(&quot;Starting file processing...&quot;)<br>    print(&quot;-&quot; * 50)<br>    <br>    success_count = 0<br>    fail_count = 0<br>    <br>    for i, file in enumerate(files, 1):<br>        print(f&quot;Processing file {i}/{len(files)}: {file}&quot;)<br>        time.sleep(0.5)  # Simulate processing<br>        <br>        if i % 5 == 0:  # Simulate occasional failure<br>            print(f&quot;  [ERROR] Failed to process {file}&quot;)<br>            fail_count += 1<br>        else:<br>            print(f&quot;  [OK] Successfully processed {file}&quot;)<br>            success_count += 1<br>    <br>    print(&quot;-&quot; * 50)<br>    print(f&quot;Summary:&quot;)<br>    print(f&quot;  Total files: {len(files)}&quot;)<br>    print(f&quot;  Successful: {success_count}&quot;)<br>    print(f&quot;  Failed: {fail_count}&quot;)<br>    print(f&quot;  Success rate: {(success_count/len(files))*100:.1f}%&quot;)</pre><pre>files = [f&quot;document_{i}.pdf&quot; for i in range(1, 21)]<br>process_files(files)</pre><p><strong>Output:</strong></p><pre>Starting file processing...<br>--------------------------------------------------<br>Processing file 1/20: document_1.pdf<br>  [OK] Successfully processed document_1.pdf<br>Processing file 2/20: document_2.pdf<br>  [OK] Successfully processed document_2.pdf<br>...<br>--------------------------------------------------<br>Summary:<br>  Total files: 20<br>  Successful: 16<br>  Failed: 4<br>  Success rate: 80.0%</pre><p><strong>Problems:</strong></p><ul><li>😴 Boring monochrome text</li><li>😕 No visual feedback during processing</li><li>😬 Hard to scan for errors</li><li>😞 Looks unprofessional</li><li>😤 Can’t tell progress at a glance</li></ul><h3>✅ The Beautiful Way (With Rich)</h3><pre>from rich.console import Console<br>from rich.progress import track<br>from rich.table import Table<br>import time<br><br>console = Console()<br>def process_files(files):<br>    console.print(&quot;[bold cyan]Starting file processing...[/bold cyan]&quot;)<br>    <br>    success_count = 0<br>    fail_count = 0<br>    <br>    for i, file in track(enumerate(files, 1), description=&quot;Processing&quot;, total=len(files)):<br>        time.sleep(0.5)<br>        <br>        if i % 5 == 0:<br>            console.print(f&quot;  [red]✗[/red] Failed: {file}&quot;)<br>            fail_count += 1<br>        else:<br>            console.print(f&quot;  [green]✓[/green] Success: {file}&quot;)<br>            success_count += 1<br>    <br>    # Create summary table<br>    table = Table(title=&quot;Processing Summary&quot;, show_header=True)<br>    table.add_column(&quot;Metric&quot;, style=&quot;cyan&quot;)<br>    table.add_column(&quot;Value&quot;, style=&quot;magenta&quot;)<br>    <br>    table.add_row(&quot;Total Files&quot;, str(len(files)))<br>    table.add_row(&quot;Successful&quot;, f&quot;[green]{success_count}[/green]&quot;)<br>    table.add_row(&quot;Failed&quot;, f&quot;[red]{fail_count}[/red]&quot;)<br>    table.add_row(&quot;Success Rate&quot;, f&quot;{(success_count/len(files))*100:.1f}%&quot;)<br>    <br>    console.print(table)</pre><pre>files = [f&quot;document_{i}.pdf&quot; for i in range(1, 21)]<br>process_files(files)</pre><p><strong>Features:</strong></p><ul><li>✅ Beautiful progress bar (automatic!)</li><li>✅ Color-coded success/failure (green/red)</li><li>✅ Professional table formatting</li><li>✅ Icons for visual clarity (✓/✗)</li><li>✅ Looks like a commercial tool</li></ul><p><strong>Same functionality. 10x better looking.</strong></p><h3>Real-World Example 1: Server Status Dashboard</h3><p><strong>Scenario:</strong> Monitor multiple servers and show their status in real-time.</p><h3>❌ The Ugly Way (45 lines)</h3><pre>import time<br>import random<br><br>servers = [<br>    {&quot;name&quot;: &quot;web-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.10&quot;},<br>    {&quot;name&quot;: &quot;web-server-02&quot;, &quot;ip&quot;: &quot;192.168.1.11&quot;},<br>    {&quot;name&quot;: &quot;db-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.20&quot;},<br>    {&quot;name&quot;: &quot;cache-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.30&quot;},<br>    {&quot;name&quot;: &quot;api-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.40&quot;},<br>]<br>def check_server(server):<br>    # Simulate health check<br>    time.sleep(0.5)<br>    status = random.choice([&quot;online&quot;, &quot;online&quot;, &quot;online&quot;, &quot;offline&quot;])<br>    response_time = random.randint(20, 200)<br>    cpu = random.randint(10, 95)<br>    memory = random.randint(30, 90)<br>    return {<br>        &quot;status&quot;: status,<br>        &quot;response_time&quot;: response_time,<br>        &quot;cpu&quot;: cpu,<br>        &quot;memory&quot;: memory<br>    }<br>print(&quot;=&quot; * 80)<br>print(&quot;SERVER HEALTH DASHBOARD&quot;)<br>print(&quot;=&quot; * 80)<br>print()<br>for server in servers:<br>    print(f&quot;Checking {server[&#39;name&#39;]}...&quot;)<br>    health = check_server(server)<br>    <br>    print(f&quot;  Server: {server[&#39;name&#39;]}&quot;)<br>    print(f&quot;  IP: {server[&#39;ip&#39;]}&quot;)<br>    print(f&quot;  Status: {health[&#39;status&#39;].upper()}&quot;)<br>    print(f&quot;  Response Time: {health[&#39;response_time&#39;]}ms&quot;)<br>    print(f&quot;  CPU Usage: {health[&#39;cpu&#39;]}%&quot;)<br>    print(f&quot;  Memory Usage: {health[&#39;memory&#39;]}%&quot;)<br>    print(&quot;-&quot; * 80)<br>print()<br>print(&quot;Dashboard updated at:&quot;, time.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))</pre><p><strong>Output:</strong></p><pre>================================================================================<br>SERVER HEALTH DASHBOARD<br>================================================================================</pre><pre>Checking web-server-01...<br>  Server: web-server-01<br>  IP: 192.168.1.10<br>  Status: ONLINE<br>  Response Time: 45ms<br>  CPU Usage: 23%<br>  Memory Usage: 67%<br>--------------------------------------------------------------------------------<br>...</pre><p>Boring. Hard to read. No visual hierarchy.</p><h3>✅ The Beautiful Way (18 lines)</h3><pre>from rich.console import Console<br>from rich.table import Table<br>from rich.live import Live<br>import time<br>import random<br><br><br>console = Console()<br>def create_dashboard(servers):<br>    table = Table(title=&quot;🖥️  Server Health Dashboard&quot;, show_header=True, header_style=&quot;bold magenta&quot;)<br>    table.add_column(&quot;Server&quot;, style=&quot;cyan&quot;, width=20)<br>    table.add_column(&quot;IP&quot;, style=&quot;blue&quot;)<br>    table.add_column(&quot;Status&quot;, justify=&quot;center&quot;)<br>    table.add_column(&quot;Response&quot;, justify=&quot;right&quot;)<br>    table.add_column(&quot;CPU&quot;, justify=&quot;right&quot;)<br>    table.add_column(&quot;Memory&quot;, justify=&quot;right&quot;)<br>    <br>    for server in servers:<br>        # Simulate health check<br>        status = random.choice([&quot;online&quot;, &quot;online&quot;, &quot;online&quot;, &quot;offline&quot;])<br>        response_time = random.randint(20, 200)<br>        cpu = random.randint(10, 95)<br>        memory = random.randint(30, 90)<br>        <br>        # Color-coded status<br>        status_display = &quot;[green]● ONLINE[/green]&quot; if status == &quot;online&quot; else &quot;[red]● OFFLINE[/red]&quot;<br>        <br>        # Color-coded metrics<br>        response_color = &quot;green&quot; if response_time &lt; 100 else &quot;yellow&quot; if response_time &lt; 150 else &quot;red&quot;<br>        cpu_color = &quot;green&quot; if cpu &lt; 70 else &quot;yellow&quot; if cpu &lt; 85 else &quot;red&quot;<br>        memory_color = &quot;green&quot; if memory &lt; 70 else &quot;yellow&quot; if memory &lt; 85 else &quot;red&quot;<br>        <br>        table.add_row(<br>            server[&quot;name&quot;],<br>            server[&quot;ip&quot;],<br>            status_display,<br>            f&quot;[{response_color}]{response_time}ms[/{response_color}]&quot;,<br>            f&quot;[{cpu_color}]{cpu}%[/{cpu_color}]&quot;,<br>            f&quot;[{memory_color}]{memory}%[/{memory_color}]&quot;<br>        )<br>    <br>    return table<br>servers = [<br>    {&quot;name&quot;: &quot;web-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.10&quot;},<br>    {&quot;name&quot;: &quot;web-server-02&quot;, &quot;ip&quot;: &quot;192.168.1.11&quot;},<br>    {&quot;name&quot;: &quot;db-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.20&quot;},<br>    {&quot;name&quot;: &quot;cache-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.30&quot;},<br>    {&quot;name&quot;: &quot;api-server-01&quot;, &quot;ip&quot;: &quot;192.168.1.40&quot;},<br>]<br>console.print(create_dashboard(servers))</pre><p><strong>Features:</strong></p><ul><li>✅ Beautiful table with borders</li><li>✅ Color-coded status (green/red)</li><li>✅ Dynamic colouring based on thresholds</li><li>✅ Icons for visual clarity</li><li>✅ Professional appearance</li><li>✅ Easy to scan at a glance</li></ul><h3>Real-World Example 2: API Testing Tool</h3><p><strong>Scenario:</strong> Test multiple API endpoints and show detailed results.</p><h3>❌ The Boring Way</h3><pre>import requests<br>import time<br><br>endpoints = [<br>    {&quot;name&quot;: &quot;Get Users&quot;, &quot;url&quot;: &quot;https://api.example.com/users&quot;},<br>    {&quot;name&quot;: &quot;Create User&quot;, &quot;url&quot;: &quot;https://api.example.com/users&quot;, &quot;method&quot;: &quot;POST&quot;},<br>    {&quot;name&quot;: &quot;Get Products&quot;, &quot;url&quot;: &quot;https://api.example.com/products&quot;},<br>    {&quot;name&quot;: &quot;Health Check&quot;, &quot;url&quot;: &quot;https://api.example.com/health&quot;},<br>]<br>print(&quot;Starting API tests...&quot;)<br>print()<br>for endpoint in endpoints:<br>    print(f&quot;Testing: {endpoint[&#39;name&#39;]}&quot;)<br>    start = time.time()<br>    <br>    try:<br>        # Simulate API call<br>        time.sleep(0.3)<br>        status = 200 if &quot;health&quot; in endpoint[&#39;name&#39;].lower() else 200<br>        duration = time.time() - start<br>        <br>        print(f&quot;  Status: {status}&quot;)<br>        print(f&quot;  Duration: {duration*1000:.2f}ms&quot;)<br>        print(f&quot;  Result: PASS&quot; if status == 200 else &quot;FAIL&quot;)<br>    except Exception as e:<br>        print(f&quot;  Error: {e}&quot;)<br>    <br>    print()<br>print(&quot;All tests completed.&quot;)</pre><h3>✅ The Beautiful Way</h3><pre>from rich.console import Console<br>from rich.table import Table<br>from rich.panel import Panel<br>from rich.progress import Progress<br>import time</pre><h3>The Rich Features That’ll Blow Your Mind</h3><h3>1. Progress Bars (Automatic!)</h3><pre>from rich.progress import track<br>import time<br><br>console = Console()<br>def test_apis(endpoints):<br>    results = []<br>    <br>    with Progress() as progress:<br>        task = progress.add_task(&quot;[cyan]Testing APIs...&quot;, total=len(endpoints))<br>        <br>        for endpoint in endpoints:<br>            start = time.time()<br>            time.sleep(0.3)  # Simulate API call<br>            <br>            duration = (time.time() - start) * 1000<br>            status = 200<br>            <br>            results.append({<br>                &quot;name&quot;: endpoint[&quot;name&quot;],<br>                &quot;status&quot;: status,<br>                &quot;duration&quot;: duration,<br>                &quot;passed&quot;: status == 200<br>            })<br>            <br>            progress.update(task, advance=1)<br>    <br>    # Create results table<br>    table = Table(title=&quot;🧪 API Test Results&quot;, show_header=True, header_style=&quot;bold cyan&quot;)<br>    table.add_column(&quot;Test&quot;, style=&quot;white&quot;, width=25)<br>    table.add_column(&quot;Status&quot;, justify=&quot;center&quot;, width=10)<br>    table.add_column(&quot;Duration&quot;, justify=&quot;right&quot;, width=15)<br>    table.add_column(&quot;Result&quot;, justify=&quot;center&quot;, width=10)<br>    <br>    for result in results:<br>        status_color = &quot;green&quot; if result[&quot;status&quot;] == 200 else &quot;red&quot;<br>        duration_color = &quot;green&quot; if result[&quot;duration&quot;] &lt; 500 else &quot;yellow&quot; if result[&quot;duration&quot;] &lt; 1000 else &quot;red&quot;<br>        <br>        table.add_row(<br>            result[&quot;name&quot;],<br>            f&quot;[{status_color}]{result[&#39;status&#39;]}[/{status_color}]&quot;,<br>            f&quot;[{duration_color}]{result[&#39;duration&#39;]:.2f}ms[/{duration_color}]&quot;,<br>            &quot;[green]✓ PASS[/green]&quot; if result[&quot;passed&quot;] else &quot;[red]✗ FAIL[/red]&quot;<br>        )<br>    <br>    console.print(table)<br>    <br>    # Summary panel<br>    passed = sum(1 for r in results if r[&quot;passed&quot;])<br>    total = len(results)<br>    <br>    summary = f&quot;[green]{passed}[/green] passed, [red]{total - passed}[/red] failed out of [cyan]{total}[/cyan] tests&quot;<br>    console.print(Panel(summary, title=&quot;Summary&quot;, border_style=&quot;green&quot;))<br>endpoints = [<br>    {&quot;name&quot;: &quot;Get Users&quot;, &quot;url&quot;: &quot;https://api.example.com/users&quot;},<br>    {&quot;name&quot;: &quot;Create User&quot;, &quot;url&quot;: &quot;https://api.example.com/users&quot;},<br>    {&quot;name&quot;: &quot;Get Products&quot;, &quot;url&quot;: &quot;https://api.example.com/products&quot;},<br>    {&quot;name&quot;: &quot;Health Check&quot;, &quot;url&quot;: &quot;https://api.example.com/health&quot;},<br>]<br>test_apis(endpoints)</pre><pre># That&#39;s it! One line!<br>for i in track(range(100), description=&quot;Processing...&quot;):<br>    time.sleep(0.1)</pre><p>You get:</p><ul><li>Progress percentage</li><li>Progress bar</li><li>Speed indicator</li><li>Time remaining</li><li>Elapsed time</li></ul><p><strong>All automatic.</strong></p><h3>2. Syntax Highlighting</h3><pre>from rich.console import Console<br>from rich.syntax import Syntax<br><br>console = Console()<br>code = &#39;&#39;&#39;<br>def hello_world():<br>    print(&quot;Hello, World!&quot;)<br>&#39;&#39;&#39;<br>syntax = Syntax(code, &quot;python&quot;, theme=&quot;monokai&quot;, line_numbers=True)<br>console.print(syntax)</pre><p>Beautiful code highlighting in your terminal. For any language.</p><h3>3. JSON Formatting</h3><pre>from rich.console import Console<br>import json<br><br>console = Console()<br>data = {<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;active&quot;: True,<br>    &quot;scores&quot;: [85, 90, 78, 92]<br>}<br>console.print_json(data=data)</pre><p>Colored, indented, beautiful JSON. One line.</p><h3>4. Tree Structures</h3><pre>from rich.tree import Tree<br>from rich.console import Console<br><br>console = Console()<br>tree = Tree(&quot;📁 Project&quot;)<br>tree.add(&quot;📄 README.md&quot;)<br>src = tree.add(&quot;📁 src&quot;)<br>src.add(&quot;📄 main.py&quot;)<br>src.add(&quot;📄 utils.py&quot;)<br>tests = tree.add(&quot;📁 tests&quot;)<br>tests.add(&quot;📄 test_main.py&quot;)<br>console.print(tree)</pre><p><strong>Output:</strong></p><pre>📁 Project<br>├── 📄 README.md<br>├── 📁 src<br>│   ├── 📄 main.py<br>│   └── 📄 utils.py<br>└── 📁 tests<br>    └── 📄 test_main.py</pre><h3>5. Panels and Boxes</h3><pre>from rich.console import Console<br>from rich.panel import Panel<br><br>console = Console()<br>console.print(Panel(&quot;This is important!&quot;, title=&quot;Warning&quot;, border_style=&quot;red&quot;))<br>console.print(Panel(&quot;Success!&quot;, title=&quot;Status&quot;, border_style=&quot;green&quot;))</pre><p>Perfect for highlighting important information.</p><h3>6. Spinners (For Long Operations)</h3><pre>from rich.console import Console<br>from rich.spinner import Spinner<br>import time<br><br>console = Console()<br>with console.status(&quot;[bold green]Working on it...&quot;) as status:<br>    time.sleep(2)<br>    console.log(&quot;Task 1 complete&quot;)<br>    <br>    time.sleep(2)<br>    console.log(&quot;Task 2 complete&quot;)<br>    <br>    time.sleep(2)<br>    console.log(&quot;All done!&quot;)</pre><p>Animated spinner while processing. Looks professional.</p><h3>Real Impact: My DevOps Tool</h3><p>Remember that CLI tool I built? Here’s what happened:</p><h3>Before Rich (Day 1–2):</h3><pre># 120 lines of code<br># Ugly print statements<br># No progress feedback<br># Hard to debug issues<br># Team feedback: &quot;meh, it works&quot;</pre><h3>After Rich (Day 3):</h3><pre># 85 lines of code (30% reduction!)<br># Beautiful color-coded output<br># Progress bars everywhere<br># Clear error highlighting<br># Team feedback: &quot;This looks professional!&quot;</pre><p><strong>Metrics:</strong></p><ul><li>✅ <strong>Code reduced by 30%</strong> (less print formatting logic)</li><li>✅ <strong>User satisfaction:</strong> 3/10 → 9/10</li><li>✅ <strong>Support tickets:</strong> Reduced by 60% (clearer output)</li><li>✅ <strong>Development time:</strong> 2 days → 5 hours</li><li>✅ <strong>Team adoption:</strong> 2 people → 15 people</li></ul><h3>The Rich Cheat Sheet</h3><p>Everything you need:</p><h3>Basic Console</h3><pre>from rich.console import Console<br><br>console = Console()<br># Colored text<br>console.print(&quot;[red]Error![/red]&quot;)<br>console.print(&quot;[green]Success![/green]&quot;)<br>console.print(&quot;[bold cyan]Important[/bold cyan]&quot;)<br># Mixed formatting<br>console.print(&quot;[bold red on white]Alert![/bold red on white]&quot;)</pre><h3>Progress Bars</h3><pre>from rich.progress import track<br><br># Simple progress<br>for item in track(items, description=&quot;Processing...&quot;):<br>    process(item)<br># Advanced progress<br>from rich.progress import Progress<br>with Progress() as progress:<br>    task1 = progress.add_task(&quot;[red]Downloading...&quot;, total=1000)<br>    task2 = progress.add_task(&quot;[green]Processing...&quot;, total=1000)<br>    <br>    while not progress.finished:<br>        progress.update(task1, advance=10)<br>        progress.update(task2, advance=5)</pre><h3>Tables</h3><pre>from rich.table import Table<br><br>table = Table(title=&quot;Users&quot;)<br>table.add_column(&quot;Name&quot;, style=&quot;cyan&quot;)<br>table.add_column(&quot;Email&quot;, style=&quot;magenta&quot;)<br>table.add_column(&quot;Status&quot;, justify=&quot;center&quot;)<br>table.add_row(&quot;John&quot;, &quot;john@example.com&quot;, &quot;[green]Active[/green]&quot;)<br>table.add_row(&quot;Jane&quot;, &quot;jane@example.com&quot;, &quot;[red]Inactive[/red]&quot;)<br>console.print(table)</pre><h3>Panels</h3><pre>from rich.panel import Panel</pre><pre>console.print(Panel(&quot;Important message&quot;, title=&quot;Alert&quot;, border_style=&quot;red&quot;))</pre><h3>Markdown Rendering</h3><pre>from rich.markdown import Markdown</pre><pre>markdown = Markdown(&quot;# Hello\n\nThis is **bold** and this is *italic*.&quot;)<br>console.print(markdown)</pre><h3>Installation</h3><pre>pip install rich</pre><p>No dependencies. Pure Python. Works everywhere.</p><h3>When to Use Rich</h3><p>Perfect for:</p><ul><li>✅ CLI tools and scripts</li><li>✅ DevOps automation</li><li>✅ Data processing pipelines</li><li>✅ API testing tools</li><li>✅ System monitoring scripts</li><li>✅ Deployment scripts</li><li>✅ Database migration tools</li><li>✅ Any terminal output</li></ul><h3>The Bottom Line</h3><p>I spent 2 days building a CLI tool with ugly print() statements.</p><p>After discovering rich:</p><ul><li>✅ <strong>Rebuilt it in 5 hours</strong> with better features</li><li>✅ <strong>30% less code</strong> (no manual formatting)</li><li>✅ <strong>Looks professional</strong> (team actually wants to use it)</li><li>✅ <strong>Easier to maintain</strong> (rich handles complexity)</li><li>✅ <strong>Users are happy</strong> (clear, beautiful output)</li></ul><p><strong>Rich makes your CLI tools look like this:</strong></p><ul><li>🎨 Beautiful colors and formatting</li><li>📊 Professional tables and charts</li><li>⏳ Animated progress bars</li><li>✨ Syntax highlighting</li><li>🎯 Clear visual hierarchy</li><li>💼 Commercial-grade appearance</li></ul><h3>Your Action Plan</h3><ol><li><strong>Install Rich:</strong> pip install rich</li><li><strong>Find your ugliest CLI script</strong></li><li><strong>Replace print() with console.print()</strong></li><li><strong>Add a progress bar</strong> with track()</li><li><strong>Add a summary table</strong></li><li><strong>Show it to your team</strong> and watch their reaction</li></ol><p>Trust me, they’ll be impressed.</p><h3>One More Thing</h3><p>Here’s the comparison that started this article:</p><p><strong>Before (Ugly):</strong></p><pre>print(&quot;Processing 100 files...&quot;)<br>for i in range(100):<br>    print(f&quot;File {i+1}/100&quot;)<br>print(&quot;Done!&quot;)</pre><p><strong>After (Beautiful):</strong></p><pre>from rich.progress import track</pre><pre>for i in track(range(100), description=&quot;Processing files&quot;):<br>    pass  # Do your work</pre><p>Same functionality. 100x better experience.</p><p>Stop making ugly CLI tools. Stop using boring print(). Stop making users squint at monochrome output.</p><p>Use Rich. Your users will love you. Your team will love you. Your manager will love you.</p><p>Make your terminal beautiful. It takes 5 minutes.</p><p><strong>What’s the ugliest CLI output you’ve seen? Share in the comments!</strong></p><p><em>Follow me for more Python tips.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c01b367d85f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wasted 3 Hours on DateTime — Then I Found Arrow]]></title>
            <link>https://medium.com/@rashmi.rout76/i-wasted-3-hours-on-datetime-then-i-found-arrow-fff8b8890da3?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff8b8890da3</guid>
            <category><![CDATA[arrow]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 09:52:52 GMT</pubDate>
            <atom:updated>2025-12-31T09:52:52.589Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Wasted 3 Hours on DateTime — Then I Found Arrow</h3><p>Last Tuesday, I spent 3 hours debugging a timezone issue in production.</p><p>The bug? Our analytics dashboard showed users from Tokyo logged in at 3 AM when they actually logged in at 11 AM.</p><p>The culprit? Python’s datetime module and my poor understanding of timezone handling.</p><pre>from datetime import datetime, timedelta<br>import pytz<br><br># This took me 45 minutes to write correctly<br>tokyo_tz = pytz.timezone(&#39;Asia/Tokyo&#39;)<br>now_utc = datetime.utcnow().replace(tzinfo=pytz.UTC)<br>now_tokyo = now_utc.astimezone(tokyo_tz)<br>three_days_ago = (now_tokyo - timedelta(days=3)).replace(hour=0, minute=0, second=0)</pre><p>Then my colleague showed me arrow.</p><p><strong>45 minutes of code became 10 seconds:</strong></p><pre>import arrow<br><br>three_days_ago = arrow.now(&#39;Asia/Tokyo&#39;).shift(days=-3).floor(&#39;day&#39;)</pre><p>I felt stupid. Then enlightened.</p><p>Let me show you why arrow will save you from datetime hell.</p><h3>The Problem with datetime</h3><p>Python’s datetime is powerful. But it&#39;s also:</p><ul><li><strong>Confusing</strong> (naive vs aware datetimes)</li><li><strong>Verbose</strong> (timezones require extra libraries)</li><li><strong>Error-prone</strong> (easy to mess up)</li><li><strong>Ugly</strong> (too much boilerplate)</li></ul><p>Here’s what most developers deal with:</p><h3>❌ The datetime Nightmare (28 lines)</h3><p><strong>Task: Get timestamps for “3 days ago” and “tomorrow” in Tokyo timezone, formatted for humans</strong></p><pre>from datetime import datetime, timedelta<br>import pytz<br><br># Get Tokyo timezone<br>tokyo_tz = pytz.timezone(&#39;Asia/Tokyo&#39;)<br># Get current time in Tokyo<br>now_utc = datetime.utcnow()<br>now_utc = now_utc.replace(tzinfo=pytz.UTC)<br>now_tokyo = now_utc.astimezone(tokyo_tz)<br># Calculate 3 days ago<br>three_days_ago = now_tokyo - timedelta(days=3)<br># Calculate tomorrow<br>tomorrow = now_tokyo + timedelta(days=1)<br># Format for humans<br>def humanize_time(dt):<br>    diff = now_tokyo - dt<br>    days = diff.days<br>    if days == 0:<br>        return &quot;today&quot;<br>    elif days == 1:<br>        return &quot;1 day ago&quot;<br>    elif days &gt; 1:<br>        return f&quot;{days} days ago&quot;<br>    else:<br>        return &quot;in the future&quot;<br>print(f&quot;Three days ago: {three_days_ago.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)} ({humanize_time(three_days_ago)})&quot;)<br>print(f&quot;Tomorrow: {tomorrow.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)}&quot;)<br>print(f&quot;Current time: {now_tokyo.strftime(&#39;%Y-%m-%d %H:%M:%S %Z&#39;)}&quot;)</pre><p><strong>Line count: 28 lines</strong><br><strong>Time to write: 25 minutes</strong><br><strong>Timezone bugs: 2</strong><br><strong>My sanity: Gone</strong></p><h3>✅ The Arrow Magic (8 lines)</h3><pre>import arrow<br><br># Get current time in Tokyo<br>now = arrow.now(&#39;Asia/Tokyo&#39;)<br># Calculate times<br>three_days_ago = now.shift(days=-3)<br>tomorrow = now.shift(days=1)<br># Format everything beautifully<br>print(f&quot;Three days ago: {three_days_ago.format(&#39;YYYY-MM-DD HH:mm:ss&#39;)} ({three_days_ago.humanize()})&quot;)<br>print(f&quot;Tomorrow: {tomorrow.format(&#39;YYYY-MM-DD HH:mm:ss&#39;)} ({tomorrow.humanize()})&quot;)<br>print(f&quot;Current time: {now.format(&#39;YYYY-MM-DD HH:mm:ss ZZZ&#39;)}&quot;)</pre><p><strong>Output:</strong></p><pre>Three days ago: 2024-12-28 15:30:45 (3 days ago)<br>Tomorrow: 2025-01-01 15:30:45 (in 23 hours)<br>Current time: 2024-12-31 15:30:45 JST</pre><p><strong>Line count: 8 lines</strong><br><strong>Time to write: 2 minutes</strong><br><strong>Timezone bugs: 0</strong><br><strong>My sanity: Restored</strong></p><h3>Why Arrow Changes Everything</h3><h3>1. Timezone Handling is Actually Simple</h3><p><strong>Old way:</strong></p><pre>from datetime import datetime<br>import pytz<br><br># Get current time in different timezones<br>utc_tz = pytz.UTC<br>tokyo_tz = pytz.timezone(&#39;Asia/Tokyo&#39;)<br>ny_tz = pytz.timezone(&#39;America/New_York&#39;)<br>now_utc = datetime.now(utc_tz)<br>now_tokyo = now_utc.astimezone(tokyo_tz)<br>now_ny = now_utc.astimezone(ny_tz)<br>print(f&quot;UTC: {now_utc.strftime(&#39;%H:%M:%S&#39;)}&quot;)<br>print(f&quot;Tokyo: {now_tokyo.strftime(&#39;%H:%M:%S&#39;)}&quot;)<br>print(f&quot;New York: {now_ny.strftime(&#39;%H:%M:%S&#39;)}&quot;)</pre><p><strong>New way:</strong></p><pre>import arrow<br><br>now_utc = arrow.utcnow()<br>now_tokyo = arrow.now(&#39;Asia/Tokyo&#39;)<br>now_ny = arrow.now(&#39;America/New_York&#39;)<br>print(f&quot;UTC: {now_utc.format(&#39;HH:mm:ss&#39;)}&quot;)<br>print(f&quot;Tokyo: {now_tokyo.format(&#39;HH:mm:ss&#39;)}&quot;)<br>print(f&quot;New York: {now_ny.format(&#39;HH:mm:ss&#39;)}&quot;)</pre><p>One function. One argument. Done.</p><h3>2. Shifting Time is Intuitive</h3><p><strong>Old way:</strong></p><pre>from datetime import datetime, timedelta<br><br>now = datetime.now()<br># Add 2 hours, 30 minutes, and 3 days<br>future = now + timedelta(days=3, hours=2, minutes=30)<br># Subtract 1 week<br>past = now - timedelta(weeks=1)<br># Add 2 months? Good luck...<br># You need dateutil or manual calculation</pre><p><strong>New way:</strong></p><pre>import arrow<br><br>now = arrow.now()<br># Add 2 hours, 30 minutes, and 3 days<br>future = now.shift(days=3, hours=2, minutes=30)<br># Subtract 1 week<br>past = now.shift(weeks=-1)<br># Add 2 months? Easy!<br>future_month = now.shift(months=2)</pre><p>Everything is .shift(). Natural. Readable.</p><h3>3. Human-Readable Formatting</h3><p><strong>Old way:</strong></p><pre>from datetime import datetime<br><br>now = datetime.now()<br>past = datetime(2024, 6, 15, 10, 30, 0)<br># Calculate &quot;time ago&quot;<br>diff = now - past<br>days = diff.days<br>hours = diff.seconds // 3600<br>if days == 0:<br>    if hours == 0:<br>        print(&quot;just now&quot;)<br>    elif hours == 1:<br>        print(&quot;1 hour ago&quot;)<br>    else:<br>        print(f&quot;{hours} hours ago&quot;)<br>elif days == 1:<br>    print(&quot;yesterday&quot;)<br>else:<br>    print(f&quot;{days} days ago&quot;)</pre><p><strong>New way:</strong></p><pre>import arrow<br><br>now = arrow.now()<br>past = arrow.get(&#39;2024-06-15 10:30:00&#39;)<br>print(past.humanize())  # &quot;6 months ago&quot;</pre><p>One method. Perfect output.</p><h3>Real-World Examples That’ll Save You Hours</h3><h3>Example 1: Log File Analysis</h3><p><strong>Scenario:</strong> Parse log files with different timestamp formats and find entries from the last 2 hours.</p><p><strong>Old way (32 lines):</strong></p><pre>from datetime import datetime, timedelta<br>import re<br><br>log_entries = [<br>    &quot;2024-12-31 13:45:23 - ERROR: Connection failed&quot;,<br>    &quot;2024-12-31T14:30:15Z - INFO: Request processed&quot;,<br>    &quot;31/Dec/2024 15:20:00 - WARNING: High memory usage&quot;,<br>]<br># Define multiple datetime formats<br>formats = [<br>    &#39;%Y-%m-%d %H:%M:%S&#39;,<br>    &#39;%Y-%m-%dT%H:%M:%SZ&#39;,<br>    &#39;%d/%b/%Y %H:%M:%S&#39;,<br>]<br>def parse_timestamp(log_line):<br>    for fmt in formats:<br>        try:<br>            # Extract timestamp (first 19-24 chars usually)<br>            timestamp_str = log_line.split(&#39; - &#39;)[0]<br>            return datetime.strptime(timestamp_str, fmt)<br>        except ValueError:<br>            continue<br>    return None<br># Get entries from last 2 hours<br>now = datetime.now()<br>two_hours_ago = now - timedelta(hours=2)<br>recent_entries = []<br>for entry in log_entries:<br>    timestamp = parse_timestamp(entry)<br>    if timestamp and timestamp &gt;= two_hours_ago:<br>        recent_entries.append(entry)<br>        <br>print(f&quot;Found {len(recent_entries)} recent entries&quot;)<br>for entry in recent_entries:<br>    print(entry)</pre><p><strong>New way (9 lines):</strong></p><pre>import arrow<br><br>log_entries = [<br>    &quot;2024-12-31 13:45:23 - ERROR: Connection failed&quot;,<br>    &quot;2024-12-31T14:30:15Z - INFO: Request processed&quot;,<br>    &quot;31/Dec/2024 15:20:00 - WARNING: High memory usage&quot;,<br>]<br>two_hours_ago = arrow.now().shift(hours=-2)<br>recent_entries = [<br>    entry for entry in log_entries<br>    if arrow.get(entry.split(&#39; - &#39;)[0]).datetime &gt;= two_hours_ago.datetime<br>]<br>print(f&quot;Found {len(recent_entries)} recent entries&quot;)<br>for entry in recent_entries:<br>    print(entry)</pre><p><strong>Arrow automatically detects the timestamp format!</strong></p><h3>Example 2: Meeting Scheduler Across Timezones</h3><p><strong>Scenario:</strong> Schedule a meeting at 2 PM Tokyo time and show it in multiple time zones.</p><p><strong>Old way (25 lines):</strong></p><pre>from datetime import datetime<br>import pytz<br><br># Create meeting time: 2 PM tomorrow in Tokyo<br>tokyo_tz = pytz.timezone(&#39;Asia/Tokyo&#39;)<br>now = datetime.now(tokyo_tz)<br>tomorrow = now.replace(hour=14, minute=0, second=0, microsecond=0)<br>tomorrow = tomorrow + timedelta(days=1)<br># Convert to other timezones<br>timezones = {<br>    &#39;Tokyo&#39;: &#39;Asia/Tokyo&#39;,<br>    &#39;New York&#39;: &#39;America/New_York&#39;,<br>    &#39;London&#39;: &#39;Europe/London&#39;,<br>    &#39;Sydney&#39;: &#39;Australia/Sydney&#39;,<br>}<br>print(&quot;Meeting Schedule:&quot;)<br>for city, tz_name in timezones.items():<br>    tz = pytz.timezone(tz_name)<br>    local_time = tomorrow.astimezone(tz)<br>    print(f&quot;{city}: {local_time.strftime(&#39;%Y-%m-%d %H:%M %Z&#39;)}&quot;)<br>    <br># Show countdown<br>time_until = tomorrow - now<br>hours = time_until.seconds // 3600<br>minutes = (time_until.seconds % 3600) // 60<br>print(f&quot;\nMeeting starts in {time_until.days} days, {hours} hours, {minutes} minutes&quot;)</pre><p><strong>New way (11 lines):</strong></p><pre>import arrow<br><br># Create meeting time: 2 PM tomorrow in Tokyo<br>meeting = arrow.now(&#39;Asia/Tokyo&#39;).shift(days=1).replace(hour=14, minute=0, second=0)<br># Convert to other timezones<br>timezones = [&#39;Asia/Tokyo&#39;, &#39;America/New_York&#39;, &#39;Europe/London&#39;, &#39;Australia/Sydney&#39;]<br>cities = [&#39;Tokyo&#39;, &#39;New York&#39;, &#39;London&#39;, &#39;Sydney&#39;]<br>print(&quot;Meeting Schedule:&quot;)<br>for city, tz in zip(cities, timezones):<br>    print(f&quot;{city}: {meeting.to(tz).format(&#39;YYYY-MM-DD HH:mm ZZZ&#39;)}&quot;)<br>print(f&quot;\nMeeting starts {meeting.humanize()}&quot;)</pre><p><strong>Output:</strong></p><pre>Meeting Schedule:<br>Tokyo: 2025-01-01 14:00 JST<br>New York: 2025-01-01 00:00 EST<br>London: 2025-01-01 05:00 GMT<br>Sydney: 2025-01-01 16:00 AEDT</pre><pre>Meeting starts in 22 hours</pre><h3>Example 3: Date Range Generation</h3><p><strong>Scenario:</strong> Generate all dates between two dates for a report.</p><p><strong>Old way (18 lines):</strong></p><pre>from datetime import datetime, timedelta<br><br>start_date = datetime(2024, 12, 1)<br>end_date = datetime(2024, 12, 10)<br># Generate date range<br>dates = []<br>current_date = start_date<br>while current_date &lt;= end_date:<br>    dates.append(current_date)<br>    current_date += timedelta(days=1)<br># Format dates<br>print(&quot;Date Range:&quot;)<br>for date in dates:<br>    day_name = date.strftime(&#39;%A&#39;)<br>    date_str = date.strftime(&#39;%Y-%m-%d&#39;)<br>    print(f&quot;{date_str} ({day_name})&quot;)</pre><p><strong>New way (6 lines):</strong></p><pre>import arrow<br><br>start = arrow.get(&#39;2024-12-01&#39;)<br>end = arrow.get(&#39;2024-12-10&#39;)<br>print(&quot;Date Range:&quot;)<br>for date in arrow.Arrow.range(&#39;day&#39;, start, end):<br>    print(f&quot;{date.format(&#39;YYYY-MM-DD&#39;)} ({date.format(&#39;dddd&#39;)})&quot;)</pre><p><strong>Output:</strong></p><pre>Date Range:<br>2024-12-01 (Sunday)<br>2024-12-02 (Monday)<br>2024-12-03 (Tuesday)<br>...<br>2024-12-10 (Tuesday)</pre><h3>The Arrow Cheat Sheet</h3><p>Everything you need to know:</p><h3>Creating Arrow Objects</h3><pre>import arrow<br><br># Current time<br>now = arrow.now()<br>now_utc = arrow.utcnow()<br>now_tokyo = arrow.now(&#39;Asia/Tokyo&#39;)<br># From timestamp<br>from_timestamp = arrow.get(1609459200)<br># From string (auto-detects format!)<br>from_string = arrow.get(&#39;2024-12-31&#39;)<br>from_string = arrow.get(&#39;2024-12-31 15:30:45&#39;)<br># From datetime object<br>from datetime import datetime<br>dt = datetime.now()<br>from_dt = arrow.get(dt)</pre><h3>Time Shifting</h3><pre>now = arrow.now()<br><br># Add time<br>future = now.shift(days=1, hours=2, minutes=30)<br>future = now.shift(weeks=2)<br>future = now.shift(months=3)<br>future = now.shift(years=1)<br># Subtract time<br>past = now.shift(days=-1)<br>past = now.shift(hours=-5)</pre><h3>Timezone Conversions</h3><pre>utc = arrow.utcnow()<br><br># Convert to timezone<br>tokyo = utc.to(&#39;Asia/Tokyo&#39;)<br>ny = utc.to(&#39;America/New_York&#39;)<br>london = utc.to(&#39;Europe/London&#39;)<br># Create directly in timezone<br>local = arrow.now(&#39;Asia/Tokyo&#39;)</pre><h3>Formatting</h3><pre>now = arrow.now()<br><br># Common formats<br>now.format(&#39;YYYY-MM-DD&#39;)              # 2024-12-31<br>now.format(&#39;YYYY-MM-DD HH:mm:ss&#39;)     # 2024-12-31 15:30:45<br>now.format(&#39;MMM DD, YYYY&#39;)            # Dec 31, 2024<br>now.format(&#39;dddd, MMMM DD&#39;)           # Tuesday, December 31<br># With timezone<br>now.format(&#39;YYYY-MM-DD HH:mm:ss ZZZ&#39;) # 2024-12-31 15:30:45 JST<br># ISO format<br>now.isoformat()                       # 2024-12-31T15:30:45+09:00</pre><h3>Humanization</h3><pre>past = arrow.now().shift(days=-3)<br>future = arrow.now().shift(hours=5)<br><br>past.humanize()        # &quot;3 days ago&quot;<br>future.humanize()      # &quot;in 5 hours&quot;<br># Custom granularity<br>past.humanize(granularity=&#39;day&#39;)    # &quot;3 days ago&quot;<br>past.humanize(granularity=&#39;hour&#39;)   # &quot;72 hours ago&quot;</pre><h3>Floor and Ceiling</h3><pre>now = arrow.now()<br><br># Floor (round down)<br>now.floor(&#39;day&#39;)      # 2024-12-31 00:00:00<br>now.floor(&#39;hour&#39;)     # 2024-12-31 15:00:00<br>now.floor(&#39;minute&#39;)   # 2024-12-31 15:30:00<br># Ceiling (round up)<br>now.ceil(&#39;day&#39;)       # 2025-01-01 00:00:00<br>now.ceil(&#39;hour&#39;)      # 2024-12-31 16:00:00</pre><h3>Ranges</h3><pre>start = arrow.get(&#39;2024-12-01&#39;)<br>end = arrow.get(&#39;2024-12-10&#39;)<br><br># Generate range<br>for date in arrow.Arrow.range(&#39;day&#39;, start, end):<br>    print(date.format(&#39;YYYY-MM-DD&#39;))<br># Hour range<br>for hour in arrow.Arrow.range(&#39;hour&#39;, start, end):<br>    print(hour.format(&#39;YYYY-MM-DD HH:00&#39;))</pre><h3>Replacing Parts</h3><pre>now = arrow.now()<br><br># Replace specific parts<br>new_time = now.replace(hour=14, minute=0, second=0)<br>new_date = now.replace(year=2025, month=1, day=1)</pre><h3>Real-World Impact: My Production Bug</h3><p>Remember that Tokyo timezone bug? Here’s what happened:</p><p><strong>The Bug:</strong></p><pre># Old code (WRONG)<br>from datetime import datetime<br><br>user_login = &quot;2024-12-31 11:00:00&quot;  # Tokyo time (JST)<br>login_dt = datetime.strptime(user_login, &#39;%Y-%m-%d %H:%M:%S&#39;)<br># This is naive! No timezone info!<br># When stored to database (UTC), it got confused<br># 11:00 JST became 11:00 UTC (wrong!)</pre><p><strong>The Fix:</strong></p><pre># New code (CORRECT)<br>import arrow<br><br>user_login = &quot;2024-12-31 11:00:00&quot;  # Tokyo time (JST)<br>login_dt = arrow.get(user_login, &#39;YYYY-MM-DD HH:mm:ss&#39;).replace(tzinfo=&#39;Asia/Tokyo&#39;)<br># Convert to UTC for storage<br>utc_time = login_dt.to(&#39;UTC&#39;)<br># Now 11:00 JST correctly becomes 02:00 UTC</pre><p><strong>Impact:</strong></p><ul><li>✅ <strong>Fixed timezone bugs</strong> across 15 different reports</li><li>✅ <strong>Reduced code</strong> by 200+ lines (datetime boilerplate removed)</li><li>✅ <strong>Eliminated confusion</strong> (team understood arrow immediately)</li><li>✅ <strong>Prevented future bugs</strong> (arrow’s API is harder to misuse)</li></ul><h3>Performance: Is Arrow Slower?</h3><p><strong>Short answer: Slightly, but it doesn’t matter.</strong></p><p>I benchmarked 100,000 operations:</p><pre>import time<br>from datetime import datetime<br>import arrow<br><br># Test: Create and format 100,000 timestamps<br># datetime version<br>start = time.time()<br>for i in range(100000):<br>    dt = datetime.now()<br>    formatted = dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>datetime_time = time.time() - start<br># arrow version<br>start = time.time()<br>for i in range(100000):<br>    arr = arrow.now()<br>    formatted = arr.format(&#39;YYYY-MM-DD HH:mm:ss&#39;)<br>arrow_time = time.time() - start<br>print(f&quot;datetime: {datetime_time:.4f}s&quot;)<br>print(f&quot;arrow: {arrow_time:.4f}s&quot;)<br>print(f&quot;Difference: {arrow_time - datetime_time:.4f}s&quot;)</pre><p><strong>Results:</strong></p><pre>datetime: 0.8234s<br>arrow: 1.2456s<br>Difference: 0.4222s (51% slower)</pre><p><strong>But here’s the thing:</strong> For 100,000 operations, arrow is 0.4 seconds slower.</p><p>In a typical web application, you’re doing maybe 10–100 datetime operations per request. The difference? <strong>Milliseconds.</strong></p><p>The readability, maintainability, and bug prevention are worth 100x more than those milliseconds.</p><h3>Common Pitfalls &amp; Solutions</h3><h3>Pitfall 1: Forgetting Timezone Awareness</h3><pre>import arrow</pre><pre># Wrong - naive datetime<br>now = arrow.now()<br>tokyo_time = now.replace(tzinfo=&#39;Asia/Tokyo&#39;)  # This doesn&#39;t convert!</pre><pre># Right - proper conversion<br>now = arrow.now(&#39;UTC&#39;)<br>tokyo_time = now.to(&#39;Asia/Tokyo&#39;)  # This converts properly</pre><h3>Pitfall 2: Comparing Arrow and datetime Objects</h3><pre>import arrow<br>from datetime import datetime</pre><pre>arr = arrow.now()<br>dt = datetime.now()</pre><pre># Wrong<br>if arr == dt:  # False (different types)<br>    print(&quot;Same time&quot;)</pre><pre># Right<br>if arr.datetime == dt:  # Compare underlying datetime<br>    print(&quot;Same time&quot;)</pre><h3>Pitfall 3: Modifying Original Objects</h3><pre>import arrow</pre><pre>now = arrow.now()</pre><pre># Arrow objects are immutable<br>future = now.shift(days=1)<br>print(now)     # Original unchanged<br>print(future)  # New object with +1 day</pre><h3>Migration Guide: datetime → arrow</h3><p>datetime arrow</p><p>datetime.now() arrow.now()</p><p>datetime.utcnow() arrow.utcnow()</p><p>datetime.now(tz) arrow.now(&#39;timezone_name&#39;)</p><p>dt.strftime(&#39;%Y-%m-%d&#39;) arr.format(&#39;YYYY-MM-DD&#39;)</p><p>dt + timedelta(days=1) arr.shift(days=1)</p><p>dt.replace(hour=0) arr.replace(hour=0)</p><p>pytz.timezone(&#39;Asia/Tokyo&#39;) arrow.now(&#39;Asia/Tokyo&#39;)</p><p>dt.astimezone(tz) arr.to(&#39;timezone_name&#39;)</p><h3>Installation</h3><pre>pip install arrow</pre><p>That’s it. No extra dependencies. No timezone database downloads. It just works.</p><h3>The Bottom Line</h3><p>I wasted 3 hours on a timezone bug because datetime is complicated.</p><p>After switching to arrow:</p><ul><li>✅ <strong>Zero timezone bugs</strong> in 6 months</li><li>✅ <strong>50% less datetime code</strong> across codebase</li><li>✅ <strong>Team onboarding faster</strong> (arrow is intuitive)</li><li>✅ <strong>No more pytz confusion</strong> (everything built-in)</li></ul><p><strong>Arrow is:</strong></p><ul><li>🎯 <strong>Simpler</strong> — Intuitive API, less cognitive load</li><li>🌍 <strong>Timezone-aware</strong> — No more naive datetime confusion</li><li>📅 <strong>Human-friendly</strong> — .humanize() for free</li><li>🔧 <strong>Practical</strong> — Designed for real-world use cases</li><li>📦 <strong>Complete</strong> — No need for pytz or dateutil</li></ul><h3>Your Action Plan</h3><ol><li><strong>Install arrow:</strong> pip install arrow</li><li><strong>Find your most complex datetime code</strong></li><li><strong>Rewrite it with arrow</strong></li><li><strong>Watch 30 lines become 5 lines</strong></li><li><strong>Never look back</strong></li></ol><p>Start with one function. You’ll immediately feel the difference.</p><h3>One Last Thing</h3><p>Here’s the bug that started it all, before and after:</p><p><strong>Before (datetime — 15 lines, 3-hour bug):</strong></p><pre>from datetime import datetime, timedelta<br>import pytz</pre><pre>tokyo_tz = pytz.timezone(&#39;Asia/Tokyo&#39;)<br>user_login = &quot;2024-12-31 11:00:00&quot;<br>login_dt = datetime.strptime(user_login, &#39;%Y-%m-%d %H:%M:%S&#39;)<br>login_dt = tokyo_tz.localize(login_dt)<br>utc_dt = login_dt.astimezone(pytz.UTC)<br>three_days_ago = utc_dt - timedelta(days=3)</pre><p><strong>After (arrow — 2 lines, 0 bugs):</strong></p><pre>import arrow</pre><pre>user_login = arrow.get(&quot;2024-12-31 11:00:00&quot;).replace(tzinfo=&#39;Asia/Tokyo&#39;)<br>three_days_ago = user_login.to(&#39;UTC&#39;).shift(days=-3)</pre><p>Stop fighting with datetime. Stop googling timezone conversions. Stop debugging time-related bugs at 2 AM.</p><p>Use arrow. Your code will thank you. Your team will thank you. Your future self will thank you.</p><p><strong>Still using datetime for everything? What’s your biggest datetime pain point? Drop it in the comments!</strong></p><p><em>Follow me for more Python tips. Next week: Why you should stop using JSON for config files.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff8b8890da3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using os.path — pathlib Will Change Your Life]]></title>
            <link>https://medium.com/@rashmi.rout76/stop-using-os-path-pathlib-will-change-your-life-5b0d12a236c8?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b0d12a236c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[pathlib]]></category>
            <category><![CDATA[python-pathlib]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 12:32:13 GMT</pubDate>
            <atom:updated>2025-12-30T12:32:13.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Using os.path — pathlib Will Change Your Life</h3><p>I spent 6 years writing Python code the hard way.</p><pre>import os<br>file_path = os.path.join(os.path.dirname(__file__), &#39;data&#39;, &#39;file.txt&#39;)<br>if os.path.exists(file_path):<br>    with open(file_path, &#39;r&#39;) as f:<br>        content = f.read()</pre><p>Ugly. Verbose. Error-prone.</p><p>Then I discovered pathlib. My file operations went from 18 lines to 7 lines. My code became readable. My bugs disappeared.</p><p>Let me show you why every modern Python developer has ditched os.path for pathlib.</p><h3>The Old Way: A Painful Journey</h3><p>Here’s what I used to write for a simple task: <strong>“Copy all .txt files from one folder to another”</strong></p><h3>❌ The os.path Nightmare (35 lines)</h3><pre>import os<br>import shutil<br><br># Define source and target directories<br>source_dir = &#39;/home/user/documents&#39;<br>target_dir = &#39;/home/user/backup&#39;<br># Check if source exists<br>if not os.path.exists(source_dir):<br>    print(f&quot;Error: {source_dir} does not exist&quot;)<br>    exit(1)<br># Create target directory if it doesn&#39;t exist<br>if not os.path.exists(target_dir):<br>    os.makedirs(target_dir)<br># Get all files in source directory (including subdirectories)<br>txt_files = []<br>for root, dirs, files in os.walk(source_dir):<br>    for file in files:<br>        if file.endswith(&#39;.txt&#39;):<br>            full_path = os.path.join(root, file)<br>            txt_files.append(full_path)<br># Copy each file<br>copied_count = 0<br>for file_path in txt_files:<br>    filename = os.path.basename(file_path)<br>    target_path = os.path.join(target_dir, filename)<br>    <br>    try:<br>        shutil.copy2(file_path, target_path)<br>        copied_count += 1<br>        print(f&quot;Copied: {filename}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error copying {filename}: {e}&quot;)<br>print(f&quot;\nTotal files copied: {copied_count}&quot;)</pre><p><strong>Line count: 35 lines</strong><br><strong>Time to write: 15 minutes</strong><br><strong>Bugs encountered: 2 (path separators on Windows, missing directory)</strong><br><strong>Readability: 3/10</strong></p><h3>✅ The pathlib Magic (12 lines)</h3><pre>from pathlib import Path<br>import shutil<br><br>source = Path(&#39;/home/user/documents&#39;)<br>target = Path(&#39;/home/user/backup&#39;)<br># Create target directory<br>target.mkdir(exist_ok=True)<br># Copy all .txt files<br>for txt_file in source.rglob(&#39;*.txt&#39;):<br>    shutil.copy2(txt_file, target / txt_file.name)<br>    print(f&quot;Copied: {txt_file.name}&quot;)<br>print(f&quot;\nTotal files copied: {len(list(target.glob(&#39;*.txt&#39;)))}&quot;)</pre><p><strong>Line count: 12 lines</strong><br><strong>Time to write: 2 minutes</strong><br><strong>Bugs encountered: 0</strong><br><strong>Readability: 10/10</strong></p><h3>Why pathlib is a Game Changer</h3><h3>1. Paths are Objects (Not Strings!)</h3><p><strong>Old way:</strong></p><pre>import os<br><br>base = &#39;/home/user&#39;<br>folder = &#39;documents&#39;<br>file = &#39;report.pdf&#39;<br># String concatenation hell<br>full_path = os.path.join(base, folder, file)<br>print(full_path)  # /home/user/documents/report.pdf</pre><p><strong>New way:</strong></p><pre>from pathlib import Path<br><br>base = Path(&#39;/home/user&#39;)<br>full_path = base / &#39;documents&#39; / &#39;report.pdf&#39;<br>print(full_path)  # /home/user/documents/report.pdf</pre><p>The / operator joins paths. Clean. Intuitive. Pythonic.</p><h3>2. Cross-Platform by Default</h3><p><strong>Old way (breaks on Windows):</strong></p><pre>import os<br><br># This only works on Unix/Linux/Mac<br>path = &#39;/home/user/documents/file.txt&#39;<br># You need to do this for Windows<br>path = os.path.join(&#39;C:&#39;, &#39;Users&#39;, &#39;user&#39;, &#39;documents&#39;, &#39;file.txt&#39;)</pre><p><strong>New way (works everywhere):</strong></p><pre>from pathlib import Path<br><br># Works on Windows, Mac, Linux automatically<br>path = Path.home() / &#39;documents&#39; / &#39;file.txt&#39;<br># Or use forward slashes - pathlib handles it<br>path = Path(&#39;C:/Users/user/documents/file.txt&#39;)  # Works on Windows!</pre><h3>3. Built-in File Operations</h3><p><strong>Old way:</strong></p><pre>import os<br><br>file_path = &#39;/home/user/data.txt&#39;<br># Check if exists<br>if os.path.exists(file_path):<br>    # Get size<br>    size = os.path.getsize(file_path)<br>    <br>    # Check if it&#39;s a file<br>    if os.path.isfile(file_path):<br>        # Read content<br>        with open(file_path, &#39;r&#39;) as f:<br>            content = f.read()</pre><p><strong>New way:</strong></p><pre>from pathlib import Path<br><br>file = Path(&#39;/home/user/data.txt&#39;)<br># Check if exists<br>if file.exists():<br>    # Get size<br>    size = file.stat().st_size<br>    <br>    # Check if it&#39;s a file<br>    if file.is_file():<br>        # Read content<br>        content = file.read_text()</pre><p>Everything you need is a method on the Path object!</p><h3>Real-World Examples That’ll Blow Your Mind</h3><h3>Example 1: Find All Python Files Modified Today</h3><p><strong>Old way (22 lines):</strong></p><pre>import os<br>import time<br>from datetime import datetime, timedelta<br><br>project_dir = &#39;/home/user/myproject&#39;<br>today = datetime.now().date()<br>python_files = []<br>for root, dirs, files in os.walk(project_dir):<br>    for file in files:<br>        if file.endswith(&#39;.py&#39;):<br>            full_path = os.path.join(root, file)<br>            <br>            # Get modification time<br>            mtime = os.path.getmtime(full_path)<br>            mod_date = datetime.fromtimestamp(mtime).date()<br>            <br>            if mod_date == today:<br>                python_files.append(full_path)<br>for file in python_files:<br>    print(file)</pre><p><strong>New way (7 lines):</strong></p><pre>from pathlib import Path<br>from datetime import datetime<br><br>project = Path(&#39;/home/user/myproject&#39;)<br>today = datetime.now().date()<br>for py_file in project.rglob(&#39;*.py&#39;):<br>    if datetime.fromtimestamp(py_file.stat().st_mtime).date() == today:<br>        print(py_file)</pre><p><strong>From 22 lines to 7 lines. 68% reduction!</strong></p><h3>Example 2: Create Project Structure</h3><p><strong>Old way (18 lines):</strong></p><pre>import os<br><br>project_name = &#39;my_app&#39;<br>base_dir = f&#39;/home/user/{project_name}&#39;<br># Create directories<br>dirs = [<br>    os.path.join(base_dir, &#39;src&#39;),<br>    os.path.join(base_dir, &#39;tests&#39;),<br>    os.path.join(base_dir, &#39;docs&#39;),<br>    os.path.join(base_dir, &#39;src&#39;, &#39;utils&#39;)<br>]<br>for dir_path in dirs:<br>    if not os.path.exists(dir_path):<br>        os.makedirs(dir_path)<br>    print(f&quot;Created: {dir_path}&quot;)</pre><p><strong>New way (5 lines):</strong></p><pre>from pathlib import Path<br><br>project = Path.home() / &#39;my_app&#39;<br>for folder in [&#39;src&#39;, &#39;tests&#39;, &#39;docs&#39;, &#39;src/utils&#39;]:<br>    (project / folder).mkdir(parents=True, exist_ok=True)<br>    print(f&quot;Created: {folder}&quot;)</pre><p><strong>From 18 lines to 5 lines. 72% reduction!</strong></p><h3>Example 3: Read/Write Files</h3><p><strong>Old way (12 lines):</strong></p><pre>import os<br><br>file_path = &#39;/home/user/config.txt&#39;<br># Write file<br>with open(file_path, &#39;w&#39;) as f:<br>    f.write(&#39;Hello, World!&#39;)<br># Read file<br>with open(file_path, &#39;r&#39;) as f:<br>    content = f.read()<br>    print(content)</pre><p><strong>New way (4 lines):</strong></p><pre>from pathlib import Path<br><br>file = Path(&#39;/home/user/config.txt&#39;)<br>file.write_text(&#39;Hello, World!&#39;)<br>content = file.read_text()<br>print(content)</pre><p>No more with open() boilerplate for simple operations!</p><h3>Example 4: Get File Information</h3><p><strong>Old way (15 lines):</strong></p><pre>import os<br><br>file_path = &#39;/home/user/document.pdf&#39;<br># Get various file info<br>filename = os.path.basename(file_path)<br>directory = os.path.dirname(file_path)<br>name, extension = os.path.splitext(filename)<br>size = os.path.getsize(file_path)<br>is_file = os.path.isfile(file_path)<br>print(f&quot;Filename: {filename}&quot;)<br>print(f&quot;Directory: {directory}&quot;)<br>print(f&quot;Name: {name}&quot;)<br>print(f&quot;Extension: {extension}&quot;)<br>print(f&quot;Size: {size} bytes&quot;)</pre><p><strong>New way (7 lines):</strong></p><pre>from pathlib import Path<br><br>file = Path(&#39;/home/user/document.pdf&#39;)<br>print(f&quot;Filename: {file.name}&quot;)<br>print(f&quot;Directory: {file.parent}&quot;)<br>print(f&quot;Name: {file.stem}&quot;)<br>print(f&quot;Extension: {file.suffix}&quot;)<br>print(f&quot;Size: {file.stat().st_size} bytes&quot;)</pre><p>Everything is a property. So clean!</p><h3>The pathlib Cheat Sheet</h3><p>Here’s everything you need to know:</p><h3>Creating Paths</h3><pre>from pathlib import Path<br><br># Current directory<br>current = Path.cwd()<br># Home directory<br>home = Path.home()<br># Specific path<br>path = Path(&#39;/home/user/file.txt&#39;)<br># Join paths with /<br>full_path = Path.home() / &#39;documents&#39; / &#39;report.pdf&#39;</pre><h3>Checking Things</h3><pre>path = Path(&#39;/home/user/file.txt&#39;)<br><br>path.exists()        # Does it exist?<br>path.is_file()       # Is it a file?<br>path.is_dir()        # Is it a directory?<br>path.is_absolute()   # Is it an absolute path?</pre><h3>Getting Information</h3><pre>path = Path(&#39;/home/user/documents/report.pdf&#39;)<br><br>path.name            # &#39;report.pdf&#39;<br>path.stem            # &#39;report&#39;<br>path.suffix          # &#39;.pdf&#39;<br>path.parent          # Path(&#39;/home/user/documents&#39;)<br>path.parts           # (&#39;/&#39;, &#39;home&#39;, &#39;user&#39;, &#39;documents&#39;, &#39;report.pdf&#39;)<br>path.stat().st_size  # File size in bytes</pre><h3>File Operations</h3><pre>path = Path(&#39;/home/user/file.txt&#39;)<br><br># Read/write text<br>content = path.read_text()<br>path.write_text(&#39;Hello!&#39;)<br># Read/write bytes<br>data = path.read_bytes()<br>path.write_bytes(b&#39;Binary data&#39;)<br># Open file (when you need more control)<br>with path.open(&#39;r&#39;) as f:<br>    content = f.read()</pre><h3>Directory Operations</h3><pre>path = Path(&#39;/home/user/mydir&#39;)<br><br># Create directory<br>path.mkdir(exist_ok=True, parents=True)<br># List files<br>for item in path.iterdir():<br>    print(item)<br># Find files (non-recursive)<br>for txt_file in path.glob(&#39;*.txt&#39;):<br>    print(txt_file)<br># Find files (recursive)<br>for py_file in path.rglob(&#39;*.py&#39;):<br>    print(py_file)</pre><h3>Path Manipulation</h3><pre>path = Path(&#39;/home/user/file.txt&#39;)<br><br># Change extension<br>new_path = path.with_suffix(&#39;.md&#39;)  # /home/user/file.md<br># Change filename<br>new_path = path.with_name(&#39;other.txt&#39;)  # /home/user/other.txt<br># Change stem (keep extension)<br>new_path = path.with_stem(&#39;other&#39;)  # /home/user/other.txt<br># Get absolute path<br>absolute = path.resolve()</pre><h3>Real-World Impact: My Refactoring Story</h3><p>Last month, I refactored our backup script:</p><h3>Before (os.path version)</h3><pre>import os<br>import shutil<br>from datetime import datetime<br><br># 45 lines of code<br># Multiple os.path.join() calls<br># Manual error handling<br># Platform-specific code<br># Hard to read</pre><h3>After (pathlib version)</h3><pre>from pathlib import Path<br>from datetime import datetime<br>import shutil<br><br># 18 lines of code<br># Clean path operations<br># Built-in error handling<br># Cross-platform<br># Self-documenting</pre><p><strong>Results:</strong></p><ul><li>✅ <strong>60% less code</strong> (45 lines → 18 lines)</li><li>✅ <strong>Eliminated 2 bugs</strong> (Windows path issues)</li><li>✅ <strong>Faster development</strong> (5 min vs 20 min)</li><li>✅ <strong>Easier maintenance</strong> (team understood it immediately)</li></ul><h3>Performance: Is pathlib Slower?</h3><p><strong>Short answer: Not noticeably.</strong></p><p>I benchmarked 10,000 file operations:</p><pre>import time<br>from pathlib import Path<br>import os<br><br># Test: Check if 10,000 files exist<br># os.path version<br>start = time.time()<br>for i in range(10000):<br>    os.path.exists(f&#39;/tmp/file_{i}.txt&#39;)<br>os_time = time.time() - start<br># pathlib version<br>start = time.time()<br>for i in range(10000):<br>    Path(f&#39;/tmp/file_{i}.txt&#39;).exists()<br>pathlib_time = time.time() - start<br>print(f&quot;os.path: {os_time:.4f}s&quot;)<br>print(f&quot;pathlib: {pathlib_time:.4f}s&quot;)</pre><p><strong>Results:</strong></p><pre>os.path: 0.0234s<br>pathlib: 0.0267s<br>Difference: 0.0033s (14% slower)</pre><p>For 10,000 operations, pathlib is 0.003 seconds slower.</p><p><strong>In real applications,</strong> you’ll never notice. The readability gain is worth it 1000x over.</p><h3>Common Pitfalls &amp; Solutions</h3><h3>Pitfall 1: Forgetting to Convert to String</h3><pre>from pathlib import Path<br><br>path = Path(&#39;/home/user/file.txt&#39;)<br># This works<br>with open(path, &#39;r&#39;) as f:  # pathlib objects work directly<br>    content = f.read()<br># But some old libraries need strings<br>import subprocess<br>subprocess.run([&#39;ls&#39;, str(path)])  # Convert with str()</pre><h3>Pitfall 2: Comparing Paths</h3><pre>from pathlib import Path<br><br># Wrong way<br>path1 = Path(&#39;/home/user/../user/file.txt&#39;)<br>path2 = Path(&#39;/home/user/file.txt&#39;)<br>print(path1 == path2)  # False<br># Right way - resolve first<br>print(path1.resolve() == path2.resolve())  # True</pre><h3>Pitfall 3: Checking if Path is a String</h3><pre>from pathlib import Path<br><br>path = Path(&#39;/home/user/file.txt&#39;)<br># Wrong<br>if path == &#39;/home/user/file.txt&#39;:  # False!<br>    print(&quot;Match&quot;)<br># Right<br>if str(path) == &#39;/home/user/file.txt&#39;:  # True<br>    print(&quot;Match&quot;)<br># Or even better<br>if path == Path(&#39;/home/user/file.txt&#39;):  # True<br>    print(&quot;Match&quot;)</pre><h3>When NOT to Use pathlib</h3><p>There are rare cases where os.path is still needed:</p><ol><li><strong>Low-level system operations</strong> — Some operations aren’t in pathlib</li><li><strong>Maximum performance</strong> — If you’re doing millions of operations</li><li><strong>Legacy code compatibility</strong> — Old code expecting strings</li></ol><p>But for 95% of use cases, pathlib is superior.</p><h3>Migration Guide: os.path → pathlib</h3><p>Here’s a quick translation table:</p><pre>os.path            pathlib <br>os.path.join(a, b) Path(a) / b   <br>os.path.exists(path) Path(path).exists()   <br>os.path.isfile(path) Path(path).is_file()   <br>os.path.isdir(path) Path(path).is_dir()   <br>os.path.basename(path) Path(path).name   <br>os.path.dirname(path) Path(path).parent   <br>os.path.splitext(path) Path(path).stem, Path(path).suffix   <br>os.path.getsize(path) Path(path).stat().st_size   <br>os.makedirs(path) Path(path).mkdir(parents=True)   <br>os.listdir(path) list(Path(path).iterdir())</pre><h3>The Bottom Line</h3><p>I wasted 6 years writing this:</p><pre>file_path = os.path.join(os.path.dirname(__file__), &#39;data&#39;, &#39;file.txt&#39;)</pre><p>When I could have written this:</p><pre>file_path = Path(__file__).parent / &#39;data&#39; / &#39;file.txt&#39;</pre><p><strong>pathlib is:</strong></p><ul><li>✅ <strong>Cleaner</strong> — More readable, less verbose</li><li>✅ <strong>Safer</strong> — Built-in error handling</li><li>✅ <strong>Modern</strong> — Pythonic object-oriented API</li><li>✅ <strong>Cross-platform</strong> — No more Windows/Unix headaches</li><li>✅ <strong>Built-in</strong> — No installation needed (Python 3.4+)</li></ul><h3>Your Action Plan</h3><ol><li><strong>Open your latest Python project</strong></li><li><strong>Find any </strong><strong>import os statements</strong></li><li><strong>Replace os.path operations with pathlib</strong></li><li><strong>Delete unnecessary code</strong></li><li><strong>Watch your code shrink by 50%</strong></li></ol><p>Start small. Convert one file. You’ll immediately see the difference.</p><h3>One More Thing</h3><p>After switching to pathlib, here’s what happened:</p><ul><li>My code reviews got faster (easier to read)</li><li>New team members understood the code immediately</li><li>Path-related bugs dropped to zero</li><li>I stopped googling “os.path.join syntax”</li></ul><p>The best part? <strong>It’s already installed.</strong> Just from pathlib import Path and start using it.</p><p>Stop fighting with string paths. Stop googling os.path methods. Stop writing 18 lines when 7 will do.</p><p>Make the switch today. Your future self will thank you.</p><p><strong>Still using os.path? What’s holding you back? Drop a comment below!</strong></p><p><em>Follow me for more Python tips that’ll make your code cleaner and your life easier. Next week: Why you should stop using print() for debugging.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b0d12a236c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Python Trick Replaced 20 Lines of Code (You’ve Never Heard Of)]]></title>
            <link>https://medium.com/@rashmi.rout76/this-python-trick-replaced-20-lines-of-code-youve-never-heard-of-fe7aa2fd3c8d?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe7aa2fd3c8d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[click]]></category>
            <category><![CDATA[top-python-libraries]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 09:35:10 GMT</pubDate>
            <atom:updated>2025-12-29T09:35:10.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ht1RRdisUc_JV9SeA46Bmg.png" /></figure><p>Everyone knows about pandas and requests. But last week, I discovered a library that made me question everything I knew about Python.</p><p>I was building a CLI tool for my team. The argument parsing code alone was 60+ lines. Messy. Ugly. Hard to maintain.</p><p>Then I found click.</p><p><strong>60 lines became 8 lines.</strong> And it looked beautiful.</p><p>Let me show you two hidden gems that most Python developers have never heard of — but should be using every day.</p><h3>Example 1: CLI Tools with Click</h3><h3>The Scenario</h3><p>You’re building a command-line tool that needs to:</p><ul><li>Accept multiple arguments</li><li>Handle optional flags</li><li>Validate input types</li><li>Show help messages</li><li>Handle errors gracefully</li><li>Support subcommands</li></ul><h3>❌ The Hard Way with argparse (45+ lines)</h3><pre>import argparse<br>import sys<br><br><br>def process_file(filename, output, verbose, format):<br>    &quot;&quot;&quot;Process a file with given options&quot;&quot;&quot;<br>    if verbose:<br>        print(f&quot;Processing {filename}...&quot;)<br>    <br>    try:<br>        with open(filename, &#39;r&#39;) as f:<br>            data = f.read()<br>            <br>        # Process data<br>        result = data.upper() if format == &#39;upper&#39; else data.lower()<br>        <br>        # Write output<br>        if output:<br>            with open(output, &#39;w&#39;) as f:<br>                f.write(result)<br>            if verbose:<br>                print(f&quot;Saved to {output}&quot;)<br>        else:<br>            print(result)<br>            <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found&quot;, file=sys.stderr)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;, file=sys.stderr)<br>        sys.exit(1)<br>def main():<br>    parser = argparse.ArgumentParser(<br>        description=&#39;Process text files&#39;,<br>        formatter_class=argparse.RawDescriptionHelpFormatter<br>    )<br>    <br>    parser.add_argument(&#39;filename&#39;, <br>                       type=str,<br>                       help=&#39;Input file to process&#39;)<br>    <br>    parser.add_argument(&#39;-o&#39;, &#39;--output&#39;,<br>                       type=str,<br>                       help=&#39;Output file (default: print to console)&#39;)<br>    <br>    parser.add_argument(&#39;-v&#39;, &#39;--verbose&#39;,<br>                       action=&#39;store_true&#39;,<br>                       help=&#39;Enable verbose output&#39;)<br>    <br>    parser.add_argument(&#39;-f&#39;, &#39;--format&#39;,<br>                       type=str,<br>                       choices=[&#39;upper&#39;, &#39;lower&#39;],<br>                       default=&#39;upper&#39;,<br>                       help=&#39;Output format (default: upper)&#39;)<br>    <br>    args = parser.parse_args()<br>    <br>    process_file(args.filename, args.output, args.verbose, args.format)<br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p><strong>Line count: 58 lines</strong><br><strong>Complexity: High</strong><br><strong>Readability: Poor (lots of boilerplate)</strong><br><strong>Type hints: None</strong></p><h3>✅ The Smart Way with Click (12 lines)</h3><pre>import click<br><br>@click.command()<br>@click.argument(&#39;filename&#39;, type=click.Path(exists=True))<br>@click.option(&#39;-o&#39;, &#39;--output&#39;, type=click.Path(), help=&#39;Output file&#39;)<br>@click.option(&#39;-v&#39;, &#39;--verbose&#39;, is_flag=True, help=&#39;Enable verbose output&#39;)<br>@click.option(&#39;-f&#39;, &#39;--format&#39;, type=click.Choice([&#39;upper&#39;, &#39;lower&#39;]), default=&#39;upper&#39;)<br>def process_file(filename, output, verbose, format):<br>    &quot;&quot;&quot;Process text files&quot;&quot;&quot;<br>    if verbose:<br>        click.echo(f&quot;Processing {filename}...&quot;)<br>    <br>    data = open(filename).read()<br>    result = data.upper() if format == &#39;upper&#39; else data.lower()<br>    <br>    if output:<br>        open(output, &#39;w&#39;).write(result)<br>        if verbose:<br>            click.echo(f&quot;Saved to {output}&quot;)<br>    else:<br>        click.echo(result)<br>if __name__ == &#39;__main__&#39;:<br>    process_file()</pre><p><strong>Line count: 22 lines (but cleaner!)</strong></p><h3>But wait — Click gets even better with decorators:</h3><pre>import click<br><br>@click.command()<br>@click.argument(&#39;filename&#39;, type=click.Path(exists=True))<br>@click.option(&#39;-o&#39;, &#39;--output&#39;, type=click.Path())<br>@click.option(&#39;-v&#39;, &#39;--verbose&#39;, is_flag=True)<br>@click.option(&#39;-f&#39;, &#39;--format&#39;, type=click.Choice([&#39;upper&#39;, &#39;lower&#39;]), default=&#39;upper&#39;)<br>def process(filename, output, verbose, format):<br>    &quot;&quot;&quot;Process text files - dead simple&quot;&quot;&quot;<br>    verbose and click.echo(f&quot;Processing {filename}...&quot;)<br>    result = open(filename).read().upper() if format == &#39;upper&#39; else open(filename).read().lower()<br>    output and open(output, &#39;w&#39;).write(result) or click.echo(result)<br>    verbose and output and click.echo(f&quot;Saved to {output}&quot;)<br>if __name__ == &#39;__main__&#39;:<br>    process()</pre><p><strong>Line count: 14 lines</strong><br> <strong>Automatic features:</strong></p><ul><li>✅ Beautiful help messages</li><li>✅ Input validation</li><li>✅ Type checking</li><li>✅ Error handling</li><li>✅ Tab completion support</li><li>✅ Testing utilities</li></ul><h3>What You Get For Free</h3><p><strong>Run it:</strong></p><pre>$ python tool.py --help</pre><p><strong>Output:</strong></p><pre>Usage: tool.py [OPTIONS] FILENAME</pre><pre>  Process text files - dead simple</pre><pre>Options:<br>  -o, --output PATH<br>  -v, --verbose<br>  -f, --format [upper|lower]<br>  --help                    Show this message and exit.</pre><p><strong>Click automatically:</strong></p><ul><li>Validates file exists</li><li>Shows formatted help</li><li>Handles errors beautifully</li><li>Supports shell completion</li><li>Validates choice options</li></ul><h3>Real-World Impact: Building a Git-like CLI</h3><p>Want multiple subcommands like git commit, git push? In argparse, that&#39;s 100+ lines. In Click:</p><pre>import click<br><br>@click.group()<br>def cli():<br>    &quot;&quot;&quot;My awesome CLI tool&quot;&quot;&quot;<br>    pass<br>@cli.command()<br>@click.argument(&#39;name&#39;)<br>def create(name):<br>    &quot;&quot;&quot;Create a new project&quot;&quot;&quot;<br>    click.echo(f&quot;Creating project: {name}&quot;)<br>@cli.command()<br>@click.option(&#39;--all&#39;, is_flag=True)<br>def list(all):<br>    &quot;&quot;&quot;List projects&quot;&quot;&quot;<br>    click.echo(&quot;Listing projects...&quot;)<br>@cli.command()<br>@click.argument(&#39;name&#39;)<br>@click.confirmation_option(prompt=&#39;Are you sure?&#39;)<br>def delete(name):<br>    &quot;&quot;&quot;Delete a project&quot;&quot;&quot;<br>    click.echo(f&quot;Deleted: {name}&quot;)<br>if __name__ == &#39;__main__&#39;:<br>    cli()</pre><p><strong>Usage:</strong></p><pre>$ python cli.py create myproject<br>$ python cli.py list --all<br>$ python cli.py delete myproject</pre><p>Try building this with argparse. I’ll wait. ☕</p><p><strong>Installation:</strong></p><pre>pip install click</pre><p><strong>Documentation:</strong> <a href="https://click.palletsprojects.com/">https://click.palletsprojects.com</a></p><p>All three examples follow the same principle:</p><h3>Low-Level Approach:</h3><ul><li>❌ 50–200 lines of code</li><li>❌ Manual error handling</li><li>❌ Deep knowledge required</li><li>❌ Platform-specific code</li><li>❌ High bug probability</li><li>❌ Poor readability</li></ul><h3>High-Level Library:</h3><ul><li>✅ 5–15 lines of code</li><li>✅ Automatic error handling</li><li>✅ Simple API</li><li>✅ Cross-platform</li><li>✅ Battle-tested</li><li>✅ Self-documenting</li></ul><h3>These libraries aren’t “cheating.” They’re:</h3><p>✅ <strong>Used by top companies</strong> (Google, Netflix, NASA)<br> ✅ <strong>Maintained by experts</strong> who know edge cases<br> ✅ <strong>Tested on millions of use cases</strong><br> ✅ <strong>Optimized for performance</strong><br> ✅ <strong>Documented thoroughly</strong></p><p>Using them makes you <strong>smarter</strong>, not lazier.</p><h3>Before You Go</h3><p>The best developers aren’t the ones who write the most code.</p><p>They’re the ones who write the <strong>least</strong> code to solve the problem.</p><p>These libraries help you do exactly that.</p><p>Stop writing 20 lines when 2 will do.</p><p>Your future self will thank you. Your team will thank you. Your sanity will thank you.</p><p><em>Follow me for more Python tips that’ll make you a 10x more productive developer.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe7aa2fd3c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using For-Loops Like This in Python]]></title>
            <link>https://medium.com/@rashmi.rout76/stop-using-for-loops-like-this-in-python-e70812139539?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70812139539</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[for-loop]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 02:25:26 GMT</pubDate>
            <atom:updated>2025-12-24T02:25:26.255Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been reviewing Python code for 5 years, and I keep seeing the same mistake over and over again.</p><p>Developers coming from C, Java, or JavaScript write Python like this:</p><pre>numbers = [1, 2, 3, 4, 5]<br>squared = []<br>for i in range(len(numbers)):<br>    squared.append(numbers[i] ** 2)</pre><p>It works. But it’s painful to read.</p><p>Let me show you why this is considered “bad Python” and what you should do instead. By the end of this article, you’ll write cleaner, faster, and more Pythonic code.</p><h3>❌ Bad Pattern #1: Using range(len())</h3><h3>The Wrong Way</h3><pre>names = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;]<br><br># DON&#39;T DO THIS<br>for i in range(len(names)):<br>    print(f&quot;Hello, {names[i]}!&quot;)</pre><p><strong>Why it’s bad:</strong></p><ul><li>Unnecessary index variable</li><li>Easy to make off-by-one errors</li><li>Not readable</li><li>Not Pythonic</li></ul><h3>The Right Way</h3><pre>names = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;]<br><br># DO THIS<br>for name in names:<br>    print(f&quot;Hello, {name}!&quot;)</pre><p><strong>Why it’s better:</strong></p><ul><li>✅ Clean and readable</li><li>✅ No index errors</li><li>✅ Expresses intent clearly</li><li>✅ Faster execution</li></ul><h3>But what if you need the index?</h3><p><strong>Wrong:</strong></p><pre>names = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;]<br><br>for i in range(len(names)):<br>    print(f&quot;{i}: {names[i]}&quot;)</pre><p><strong>Right:</strong></p><pre>names = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;]<br><br>for i, name in enumerate(names):<br>    print(f&quot;{i}: {name}&quot;)</pre><p>The The enumerate() function gives you both the index and value. Clean and efficient.</p><h3>❌ Bad Pattern #2: Building Lists with Append in Loops</h3><h3>The Wrong Way</h3><pre>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>evens = []</pre><pre># DON&#39;T DO THIS<br>for num in numbers:<br>    if num % 2 == 0:<br>        evens.append(num)<br>print(evens)  # [2, 4, 6, 8, 10]</pre><p><strong>Why it’s bad:</strong></p><ul><li>Verbose</li><li>Harder to understand at a glance</li><li>Slower for large datasets</li></ul><h3>The Right Way</h3><pre>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre><pre># DO THIS<br>evens = [num for num in numbers if num % 2 == 0]<br>print(evens)  # [2, 4, 6, 8, 10]</pre><p><strong>Why it’s better:</strong></p><ul><li>✅ One line vs four</li><li>✅ Intent is immediately clear</li><li>✅ 20–30% faster</li><li>✅ Pythonic</li></ul><h3>Real-World Example: Transforming Data</h3><p><strong>Wrong:</strong></p><pre>prices = [19.99, 24.99, 9.99, 39.99, 14.99]<br>discounted = []</pre><pre>for price in prices:<br>    new_price = price * 0.9  # 10% discount<br>    discounted.append(round(new_price, 2))<br>print(discounted)</pre><p><strong>Right:</strong></p><pre>prices = [19.99, 24.99, 9.99, 39.99, 14.99]<br><br>discounted = [round(price * 0.9, 2) for price in prices]<br>print(discounted)</pre><p>From 5 lines to 1 line. Same result. Much cleaner.</p><h3>❌ Bad Pattern #3: Nested Loops for Matrix Operations</h3><h3>The Wrong Way</h3><pre>matrix = [<br>    [1, 2, 3],<br>    [4, 5, 6],<br>    [7, 8, 9]<br>]</pre><pre>doubled = []<br># DON&#39;T DO THIS<br>for row in matrix:<br>    new_row = []<br>    for num in row:<br>        new_row.append(num * 2)<br>    doubled.append(new_row)<br>print(doubled)<br># [[2, 4, 6], [8, 10, 12], [14, 16, 18]]</pre><p><strong>Why it’s bad:</strong></p><ul><li>7 lines of code</li><li>Multiple temporary variables</li><li>Hard to read nested structure</li></ul><h3>The Right Way</h3><pre>matrix = [<br>    [1, 2, 3],<br>    [4, 5, 6],<br>    [7, 8, 9]<br>]<br><br># DO THIS<br>doubled = [[num * 2 for num in row] for row in matrix]<br>print(doubled)<br># [[2, 4, 6], [8, 10, 12], [14, 16, 18]]</pre><p><strong>Why it’s better:</strong></p><ul><li>✅ 1 line vs 7 lines</li><li>✅ Nested comprehension is readable</li><li>✅ Faster execution</li><li>✅ No temporary variables</li></ul><h3>❌ Bad Pattern #4: Looping to Find Maximum/Minimum</h3><h3>The Wrong Way</h3><pre>scores = [85, 92, 78, 90, 88, 95, 73]<br><br># DON&#39;T DO THIS<br>highest = scores[0]<br>for score in scores:<br>    if score &gt; highest:<br>        highest = score<br>print(f&quot;Highest score: {highest}&quot;)</pre><p><strong>Why it’s bad:</strong></p><ul><li>Reinventing the wheel</li><li>Verbose</li><li>Prone to bugs (what if the list is empty?)</li></ul><h3>The Right Way</h3><pre>scores = [85, 92, 78, 90, 88, 95, 73]<br><br># DO THIS<br>highest = max(scores)<br>print(f&quot;Highest score: {highest}&quot;)</pre><p><strong>Even better with complex data:</strong></p><pre>students = [<br>    {&#39;name&#39;: &#39;Alice&#39;, &#39;score&#39;: 85},<br>    {&#39;name&#39;: &#39;Bob&#39;, &#39;score&#39;: 92},<br>    {&#39;name&#39;: &#39;Charlie&#39;, &#39;score&#39;: 78}<br>]<br><br><br># Find student with highest score<br>top_student = max(students, key=lambda x: x[&#39;score&#39;])<br>print(top_student)  # {&#39;name&#39;: &#39;Bob&#39;, &#39;score&#39;: 92}</pre><h3>❌ Bad Pattern #5: Looping to Check Conditions</h3><h3>The Wrong Way</h3><pre>numbers = [2, 4, 6, 8, 10]<br><br># DON&#39;T DO THIS - Check if all are even<br>all_even = True<br>for num in numbers:<br>    if num % 2 != 0:<br>        all_even = False<br>        break<br>print(all_even)  # True</pre><pre>numbers = [1, 2, 3, 4, 5]<br><br># DON&#39;T DO THIS - Check if any are even<br>has_even = False<br>for num in numbers:<br>    if num % 2 == 0:<br>        has_even = True<br>        break<br>print(has_even)  # True</pre><h3>The Right Way</h3><pre>numbers = [2, 4, 6, 8, 10]<br><br># DO THIS<br>all_even = all(num % 2 == 0 for num in numbers)<br>print(all_even)  # True</pre><pre>numbers = [1, 2, 3, 4, 5]<br><br># DO THIS<br>has_even = any(num % 2 == 0 for num in numbers)<br>print(has_even)  # True</pre><p><strong>Why it’s better:</strong></p><ul><li>✅ Built-in functions (all(), any())</li><li>✅ Short-circuit evaluation (stops early)</li><li>✅ Crystal clear intent</li><li>✅ One line vs multiple</li></ul><h3>❌ Bad Pattern #6: Manual Dictionary Building</h3><h3>The Wrong Way</h3><pre>keys = [&#39;name&#39;, &#39;age&#39;, &#39;city&#39;]<br>values = [&#39;Alice&#39;, 30, &#39;New York&#39;]<br><br><br># DON&#39;T DO THIS<br>person = {}<br>for i in range(len(keys)):<br>    person[keys[i]] = values[i]<br>print(person)<br># {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30, &#39;city&#39;: &#39;New York&#39;}</pre><h3>The Right Way</h3><pre>keys = [&#39;name&#39;, &#39;age&#39;, &#39;city&#39;]<br>values = [&#39;Alice&#39;, 30, &#39;New York&#39;]<br><br># DO THIS<br>person = dict(zip(keys, values))<br>print(person)<br># {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30, &#39;city&#39;: &#39;New York&#39;}</pre><p><strong>Or use dictionary comprehension:</strong></p><pre>person = {k: v for k, v in zip(keys, values)}</pre><h3>❌ Bad Pattern #7: Looping to Sum or Count</h3><h3>The Wrong Way</h3><pre>prices = [19.99, 24.99, 9.99, 39.99, 14.99]<br><br># DON&#39;T DO THIS - Calculate total<br>total = 0<br>for price in prices:<br>    total += price<br>print(f&quot;Total: ${total}&quot;)</pre><pre>items = [&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;banana&#39;, &#39;apple&#39;]<br><br><br># DON&#39;T DO THIS - Count occurrences<br>apple_count = 0<br>for item in items:<br>    if item == &#39;apple&#39;:<br>        apple_count += 1<br>print(f&quot;Apples: {apple_count}&quot;)</pre><h3>The Right Way</h3><pre>prices = [19.99, 24.99, 9.99, 39.99, 14.99]<br><br># DO THIS<br>total = sum(prices)<br>print(f&quot;Total: ${total}&quot;)</pre><pre>items = [&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;banana&#39;, &#39;apple&#39;]<br><br># DO THIS<br>apple_count = items.count(&#39;apple&#39;)<br>print(f&quot;Apples: {apple_count}&quot;)</pre><p><strong>For counting multiple items:</strong></p><pre>from collections import Counter<br><br>items = [&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;banana&#39;, &#39;apple&#39;]<br>counts = Counter(items)<br>print(counts)  # Counter({&#39;apple&#39;: 3, &#39;banana&#39;: 2, &#39;orange&#39;: 1})</pre><h3>Performance Comparison</h3><p>I ran benchmarks on a list of 1 million numbers. Here are the results:</p><pre>import time</pre><pre>numbers = list(range(1000000))<br># Method 1: Loop with append<br>start = time.time()<br>squared = []<br>for num in numbers:<br>    squared.append(num ** 2)<br>loop_time = time.time() - start<br># Method 2: List comprehension<br>start = time.time()<br>squared = [num ** 2 for num in numbers]<br>comp_time = time.time() - start<br>print(f&quot;Loop with append: {loop_time:.4f} seconds&quot;)<br>print(f&quot;List comprehension: {comp_time:.4f} seconds&quot;)<br>print(f&quot;Speedup: {loop_time/comp_time:.2f}x faster&quot;)</pre><p><strong>Results:</strong></p><pre>Loop with append: 0.1847 seconds<br>List comprehension: 0.1203 seconds<br>Speedup: 1.54x faster</pre><p>List comprehensions are <strong>30–50% faster</strong> because:</p><ul><li>They’re optimised in C</li><li>No repeated function calls (append)</li><li>Better memory allocation</li></ul><h3>The Pythonic Way: When to Use What</h3><p>Task Wrong ❌ Right ✅ Iterate list for i in range(len(list)) for item in list Get index + value for i in range(len(list)) for i, item in enumerate(list) Transform list Loop + append List comprehension Filter list Loop + if + append List comp with if Find max/min Manual loop max() / min() Check all/any Loop + break all() / any() Sum numbers Loop with += sum() Count items Loop with counter .count() or Counter() Build dict Loop + dict[key] = val dict(zip()) or dict comp</p><h3>The Real-World Impact</h3><p>Last month, I refactored our data processing pipeline:</p><p><strong>Before:</strong></p><ul><li>450 lines of nested loops</li><li>12 seconds processing time</li><li>Hard to debug</li></ul><p><strong>After:</strong></p><ul><li>180 lines with comprehensions and built-ins</li><li>7 seconds processing time</li><li>Much easier to maintain</li></ul><p>The code became:</p><ul><li>✅ 60% shorter</li><li>✅ 40% faster</li><li>✅ 10x easier to understand</li></ul><h3>When Loops Are Actually Better</h3><p>Don’t go crazy avoiding loops. Use them when:</p><ol><li><strong>Complex logic</strong> that doesn’t fit in one line</li></ol><pre>for user in users:<br>    if user.is_active:<br>        send_email(user)<br>        log_activity(user)<br>        update_database(user)</pre><ol><li><strong>Side effects</strong> (printing, writing files, API calls)</li></ol><pre>for file in files:<br>    process_file(file)<br>    upload_to_cloud(file)</pre><ol><li><strong>Early termination</strong> with complex conditions</li></ol><pre>for item in large_list:<br>    if complex_condition(item):<br>        result = item<br>        break</pre><p>The key: <strong>If you’re building a new list/dict, use comprehensions. If you’re doing actions, use loops.</strong></p><h3>Quick Reference Cheat Sheet</h3><pre># ❌ DON&#39;T<br>for i in range(len(items)):<br>    print(items[i])</pre><pre># ✅ DO<br>for item in items:<br>    print(item)</pre><pre># ❌ DON&#39;T<br>result = []<br>for x in items:<br>    result.append(x * 2)</pre><pre># ✅ DO<br>result = [x * 2 for x in items]</pre><pre># ❌ DON&#39;T<br>total = 0<br>for x in numbers:<br>    total += x</pre><pre># ✅ DO<br>total = sum(numbers)</pre><pre># ❌ DON&#39;T<br>found = False<br>for x in items:<br>    if condition(x):<br>        found = True<br>        break</pre><pre># ✅ DO<br>found = any(condition(x) for x in items)</pre><h3>The Bottom Line</h3><p>Stop writing Python like it’s C or Java.</p><p>Python gives you powerful tools:</p><ul><li>List comprehensions</li><li>Built-in functions</li><li>Generator expressions</li><li>Dictionary comprehensions</li></ul><p>Use them.</p><p>Your code will be:</p><ul><li><strong>Shorter</strong> — Less to write and maintain</li><li><strong>Faster</strong> — Optimised in C</li><li><strong>Cleaner</strong> — More readable</li><li><strong>Pythonic</strong> — What the community expects</li></ul><h3>Your Action Plan</h3><ol><li><strong>Review your last Python file</strong></li><li><strong>Find loops that build lists</strong> → Replace with comprehensions</li><li><strong>Find </strong><strong>range(len()) patterns</strong> → Use direct iteration or enumerate()</li><li><strong>Find manual max/min/sum</strong> → Use built-in functions</li></ol><p>Start small. One file at a time. Your future self will thank you.</p><p><strong>What’s the most common loop pattern you use? Share in the comments!</strong></p><p><em>Follow me for more Python tips that’ll make you a better developer.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70812139539" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Python Trick Replaced 20 Lines of Code]]></title>
            <link>https://medium.com/@rashmi.rout76/this-python-trick-replaced-20-lines-of-code-c9cd1da6fc1b?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9cd1da6fc1b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-pandas]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 02:06:04 GMT</pubDate>
            <atom:updated>2025-12-24T02:06:04.464Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, I was building a data processing script for my company’s sales reports. What started as a simple task turned into 50+ lines of messy code. Then my colleague showed me a trick that reduced it to just 2 lines.</p><p>I felt like an idiot. But also enlightened.</p><p>Let me show you two real-world examples where the right Python library transforms verbose nightmares into elegant one-liners.</p><h3>Example 1: Processing CSV Files with Pandas</h3><h3>The Problem</h3><p>You have a CSV file with sales data. You need to:</p><ul><li>Read the CSV</li><li>Filter rows where sales &gt; 1000</li><li>Group by region</li><li>Calculate average sales per region</li><li>Sort by average (descending)</li><li>Save to a new CSV</li></ul><h3>The Traditional Approach (25+ lines)</h3><pre>import csv</pre><pre># Read the CSV file<br>sales_data = []<br>with open(&#39;sales.csv&#39;, &#39;r&#39;) as file:<br>    reader = csv.DictReader(file)<br>    for row in reader:<br>        sales_data.append(row)<br># Filter sales &gt; 1000<br>filtered_data = []<br>for row in sales_data:<br>    if float(row[&#39;sales&#39;]) &gt; 1000:<br>        filtered_data.append(row)<br># Group by region and calculate averages<br>region_totals = {}<br>region_counts = {}<br>for row in filtered_data:<br>    region = row[&#39;region&#39;]<br>    sales = float(row[&#39;sales&#39;])<br>    <br>    if region not in region_totals:<br>        region_totals[region] = 0<br>        region_counts[region] = 0<br>    <br>    region_totals[region] += sales<br>    region_counts[region] += 1<br># Calculate averages<br>region_averages = {}<br>for region in region_totals:<br>    region_averages[region] = region_totals[region] / region_counts[region]<br># Sort by average descending<br>sorted_regions = sorted(region_averages.items(), key=lambda x: x[1], reverse=True)<br># Write to new CSV<br>with open(&#39;output.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.writer(file)<br>    writer.writerow([&#39;Region&#39;, &#39;Average Sales&#39;])<br>    for region, avg in sorted_regions:<br>        writer.writerow([region, avg])<br>print(&quot;Done! Results saved to output.csv&quot;)</pre><p><strong>Lines of code: 43</strong><br> <strong>Time to write: 15–20 minutes</strong><br> <strong>Bugs I encountered: 3 (type conversion, dictionary initialisation, sorting)</strong></p><h3>The Pandas Approach (2 lines)</h3><pre>import pandas as pd</pre><pre>df = pd.read_csv(&#39;sales.csv&#39;)<br>df[df[&#39;sales&#39;] &gt; 1000].groupby(&#39;region&#39;)[&#39;sales&#39;].mean().sort_values(ascending=False).to_csv(&#39;output.csv&#39;)</pre><p><strong>Lines of code: 2</strong><br> <strong>Time to write: 30 seconds</strong><br> <strong>Bugs encountered: 0</strong></p><h3>Why This Works</h3><p>Pandas is designed specifically for data manipulation. Here’s what happens behind the scenes:</p><ol><li><strong>pd.read_csv(&#39;sales.csv&#39;)</strong> - Reads and parses the CSV automatically</li><li><strong>df[df[&#39;sales&#39;] &gt; 1000]</strong> - Filters rows using boolean indexing</li><li><strong>.groupby(&#39;region&#39;)[&#39;sales&#39;]</strong> - Groups by region, selects the sales column</li><li><strong>.mean()</strong> - Calculates the average for each group</li><li><strong>.sort_values(ascending=False)</strong> - Sorts descending</li><li><strong>.to_csv(&#39;output.csv&#39;)</strong> - Exports to CSV</li></ol><p>All optimised C code under the hood, making it faster than pure Python loops.</p><h3>Real Impact</h3><p>When I switched to Pandas:</p><ul><li><strong>Development time</strong>: Reduced from 20 minutes to 2 minutes</li><li><strong>Code maintenance</strong>: Much easier to read and modify</li><li><strong>Performance</strong>: 10x faster on large datasets (tested on 100K rows)</li><li><strong>Bugs</strong>: Eliminated type conversion and edge case issues</li></ul><h3>When to Use These Libraries</h3><p><strong>Use Pandas when:</strong></p><ul><li>Working with CSV, Excel, and SQL data</li><li>Need to aggregate, filter, or transform data</li><li>Handling time series analysis</li><li>Creating data visualisations</li></ul><h3>The One Thing You Should Remember</h3><blockquote><em>“Don’t reinvent the wheel. Stand on the shoulders of giants.”</em></blockquote><p>Python has 400,000+ packages on PyPI. Before writing 50 lines of code, ask yourself:</p><p><strong>“Has someone already solved this problem?”</strong></p><p>The answer is usually <strong>yes</strong>.</p><h3>Your Turn</h3><p>Look at your recent projects. Find a section where you:</p><ul><li>Loop through data manually</li><li>Parse files line by line</li><li>Manually calculate statistics</li></ul><p>Then ask: <strong>“Is there a library for this?”</strong></p><p>Chances are, you’ll find something that replaces 20+ lines with 2.</p><h3>Quick Start Guide</h3><p><strong>Install these essential libraries:</strong></p><pre>pip install pandas</pre><p><strong>Most common use cases:</strong></p><ul><li>Data processing → Pandas</li></ul><h3>Conclusion</h3><p>That 2-line Pandas solution saved me hours. Not just in writing the initial code, but in:</p><ul><li>Debugging (fewer bugs)</li><li>Testing (less code to test)</li><li>Maintenance (easier to modify)</li><li>Onboarding (new devs understand it instantly)</li></ul><p>The best code is <strong>no code</strong>. The second best is <strong>someone else’s well-tested code</strong>.</p><p>Stop writing 20 lines when 2 will do.</p><p><strong>What’s your favourite Python library that saves you time? Drop it in the comments!</strong></p><p><em>If this helped you, follow me for more Python tips that’ll make your code cleaner and your life easier.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9cd1da6fc1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn List Comprehensions]]></title>
            <link>https://medium.com/@rashmi.rout76/learn-list-comprehensions-922f08f49f00?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/922f08f49f00</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 09:21:24 GMT</pubDate>
            <atom:updated>2025-12-22T09:21:24.875Z</atom:updated>
            <content:encoded><![CDATA[<p>List comprehensions are the most widely used by Python developers, although they do not provide any time advantage. It&#39;s an efficient way of writing your code instead of writing many lines of code.</p><p>Let&#39;s Learn how to write it.</p><pre>list1 = [1,2,3,4,5,6]</pre><pre># increase by one.<br>new_list1 = []<br>for i in list1:<br>    a = i+1<br>    new_list1.append(a)</pre><p>Let&#39;s convert it to a list comprehension</p><pre>cmp_new_list1 = [i+1 for i in list1]</pre><p>See the output below</p><pre>print(&quot;New List = &quot;, new_list1)<br>print(&quot;New List comprehension= &quot;, cmp_new_list1)</pre><p>New List = [2, 3, 4, 5, 6, 7]<br>New List comprehension= [2, 3, 4, 5, 6, 7]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922f08f49f00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Python Scripts to Automate Boring Tasks (No External Libraries!)]]></title>
            <link>https://medium.com/@rashmi.rout76/10-python-scripts-to-automate-boring-tasks-no-external-libraries-34d5c897c567?source=rss-4118f35d9ccf------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d5c897c567</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Rashmi Ranjan Rout]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 09:19:20 GMT</pubDate>
            <atom:updated>2025-12-22T09:19:20.777Z</atom:updated>
            <content:encoded><![CDATA[<p>Tired of repetitive tasks eating up your time? Here are 10 clean Python scripts that automate common boring tasks using only the standard library. Each script is under 10 lines and ready to use immediately.</p><ol><li><strong>Batch File Renamer</strong></li></ol><p><strong>Task</strong>: Rename all files in a folder with sequential numbering<br> <strong>Input</strong>: Folder path, optional prefix<br> <strong>Output</strong>: Files renamed as prefix_001.ext, prefix_002.ext, etc.</p><pre>import os<br>import sys<br><br>folder = sys.argv[1] if len(sys.argv) &gt; 1 else &#39;.&#39;<br>prefix = sys.argv[2] if len(sys.argv) &gt; 2 else &#39;file&#39;<br><br>files = sorted([f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))])<br>for i, filename in enumerate(files, 1):<br>    ext = os.path.splitext(filename)[1]<br>    new_name = f&quot;{prefix}_{i:03d}{ext}&quot;<br>    os.rename(os.path.join(folder, filename), os.path.join(folder, new_name))<br>    print(f&quot;Renamed: {filename} -&gt; {new_name}&quot;)</pre><p><strong>Usage</strong>: python rename.py /path/to/folder MyFile</p><p><strong>2. CSV to JSON Converter</strong></p><p><strong>Task</strong>: Convert CSV files to JSON format<br> <strong>Input</strong>: CSV file path<br> <strong>Output</strong>: JSON file with the same data</p><pre>import csv<br>import json<br>import sys<br><br>input_file = sys.argv[1] if len(sys.argv) &gt; 1 else &#39;input.csv&#39;<br>output_file = sys.argv[2] if len(sys.argv) &gt; 2 else &#39;output.json&#39;<br><br>with open(input_file, &#39;r&#39;) as csv_file:<br>    csv_reader = csv.DictReader(csv_file)<br>    data = list(csv_reader)<br><br>with open(output_file, &#39;w&#39;) as json_file:<br>    json.dump(data, json_file, indent=2)<br>    print(f&quot;Converted {input_file} to {output_file}&quot;)</pre><p><strong>Usage</strong>: python csv_to_json.py data.csv output.json</p><p><strong>3. Email Extractor</strong></p><p><strong>Task</strong>: Extract all email addresses from text files<br> <strong>Input</strong>: Text file or folder containing text files<br> <strong>Output</strong>: List of unique email addresses</p><pre>import re<br>import sys<br><br>file_path = sys.argv[1] if len(sys.argv) &gt; 1 else &#39;input.txt&#39;<br>email_pattern = r&#39;\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b&#39;<br><br>with open(file_path, &#39;r&#39;) as file:<br>    content = file.read()<br>    emails = set(re.findall(email_pattern, content))<br><br>for email in sorted(emails):<br>    print(email)</pre><p><strong>Usage</strong>: python extract_emails.py document.txt</p><p><strong>4. Duplicate File Finder</strong></p><p><strong>Task</strong>: Find duplicate files in a directory by comparing content<br> <strong>Input</strong>: Folder path<br> <strong>Output</strong>: Groups of duplicate files</p><pre>import os<br>import hashlib<br>import sys<br>from collections import defaultdict<br><br>folder = sys.argv[1] if len(sys.argv) &gt; 1 else &#39;.&#39;<br>hashes = defaultdict(list)<br><br>for root, _, files in os.walk(folder):<br>    for filename in files:<br>        path = os.path.join(root, filename)<br>        with open(path, &#39;rb&#39;) as f:<br>            file_hash = hashlib.md5(f.read()).hexdigest()<br>            hashes[file_hash].append(path)<br><br>for file_list in hashes.values():<br>    if len(file_list) &gt; 1:<br>        print(f&quot;Duplicates found: {file_list}&quot;)</pre><p><strong>Usage</strong>: python find_duplicates.py /path/to/folder</p><p>Found this helpful? Follow me for more Python automation tips and tricks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d5c897c567" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>