<?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 Vaibhav Kumar on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Kumar on Medium]]></description>
        <link>https://medium.com/@vaibhavkumar_83394?source=rss-15f705ccb040------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qMUCqI-SO9bkR_gX.</url>
            <title>Stories by Vaibhav Kumar on Medium</title>
            <link>https://medium.com/@vaibhavkumar_83394?source=rss-15f705ccb040------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:49:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavkumar_83394/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[Beyond Accuracy: A Practical Guide to Functional Testing for AI Models with Transformers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">How to ensure your models are reliable, consistent, and robust using the Hugging Face library. &#x1F9EA;</p><p class="medium-feed-link"><a href="https://medium.com/@vaibhavkumar_83394/beyond-accuracy-a-practical-guide-to-functional-testing-for-ai-models-with-transformers-7f6ef671038d?source=rss-15f705ccb040------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vaibhavkumar_83394/beyond-accuracy-a-practical-guide-to-functional-testing-for-ai-models-with-transformers-7f6ef671038d?source=rss-15f705ccb040------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6ef671038d</guid>
            <dc:creator><![CDATA[Vaibhav Kumar]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 12:57:05 GMT</pubDate>
            <atom:updated>2025-08-02T12:57:05.805Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[7 Awesome Python Decorators That Will Transform Your Code]]></title>
            <link>https://medium.com/@vaibhavkumar_83394/7-awesome-python-decorators-that-will-transform-your-code-9d404d0908e8?source=rss-15f705ccb040------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d404d0908e8</guid>
            <dc:creator><![CDATA[Vaibhav Kumar]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 03:52:47 GMT</pubDate>
            <atom:updated>2025-03-06T03:52:47.113Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever felt that your Python code could use a little magic? Decorators are like secret ingredients that not only clean up your code but also add powerful functionality — all without modifying your original logic. In this post, we’ll explore seven built-in Python decorators that can help you write more elegant, efficient, and Pythonic code. We’ll walk through updated examples for each decorator and show you their outputs. Let’s dive in!</p><h3>1. @property: Intuitive Attribute Access</h3><p>Imagine being able to call methods like attributes while still keeping the power of adding validation or conversion logic. The @property decorator makes that possible. Check out this refreshed version of a temperature converter that validates inputs and converts between Celsius and Fahrenheit:</p><pre>class Temperature:<br>    def __init__(self, celsius=0):<br>        self._celsius = celsius<br>    @property<br>    def celsius(self):<br>        return self._celsius<br>    @celsius.setter<br>    def celsius(self, value):<br>        if value &lt; -273.15:<br>            raise ValueError(&quot;Temperature below absolute zero is not possible!&quot;)<br>        self._celsius = value<br>    @property<br>    def fahrenheit(self):<br>        return self._celsius * 9 / 5 + 32<br>    @fahrenheit.setter<br>    def fahrenheit(self, value):<br>        self.celsius = (value - 32) * 5 / 9<br># Demonstration<br>weather = Temperature()<br>weather.celsius = 25  # Set temperature in Celsius with validation<br>print(f&quot;{weather.celsius}°C is equivalent to {weather.fahrenheit}°F&quot;)</pre><p><strong>Output:</strong></p><pre>25°C is equivalent to 77.0°F</pre><h3>2. @cached_property: Efficient Lazy Computation</h3><p>Sometimes, you have a computation that’s heavy and shouldn’t be repeated unnecessarily. The @cached_property decorator from the functools module computes the value once and caches it for future access. Here’s a revised example that simulates a heavy computation:</p><pre>from functools import cached_property<br>import time<br><br>class DataCruncher:<br>    def __init__(self, numbers):<br>        self.numbers = numbers<br>    @cached_property<br>    def heavy_computation(self):<br>        print(&quot;Performing a heavy computation...&quot;)<br>        time.sleep(2)  # Simulate a time-consuming calculation<br>        return sum(x * x for x in self.numbers)<br># Demonstration<br>cruncher = DataCruncher(range(1000000))<br>print(&quot;First access:&quot;)<br>start = time.time()<br>result = cruncher.heavy_computation<br>end = time.time()<br>print(f&quot;Result: {result}, Time taken: {end - start:.2f}s&quot;)<br>print(&quot;\nSecond access (cached):&quot;)<br>start = time.time()<br>result = cruncher.heavy_computation<br>end = time.time()<br>print(f&quot;Result: {result}, Time taken: {end - start:.2f}s&quot;)</pre><p><strong>Output:</strong></p><pre>First access:<br>Performing a heavy computation...<br>Result: 333332833333500000, Time taken: 2.17s<br><br>Second access (cached):<br>Result: 333332833333500000, Time taken: 0.00s</pre><h3>3. @lru_cache: Speed Up Recursion with Memoization</h3><p>Recursive functions like the Fibonacci sequence can be painfully slow without optimization. The @lru_cache decorator memorizes previous results, making repeated calls almost instantaneous. Here’s a revamped Fibonacci example:</p><pre>from functools import lru_cache<br>import time<br><br>@lru_cache(maxsize=128)<br>def fibonacci(n):<br>    if n &lt; 2:<br>        return n<br>    return fibonacci(n - 1) + fibonacci(n - 2)<br># Demonstration<br>start = time.time()<br>fib35 = fibonacci(35)<br>end = time.time()<br>print(f&quot;Fibonacci(35) = {fib35}, calculated in {end - start:.6f} seconds&quot;)<br>print(f&quot;Cache info: {fibonacci.cache_info()}&quot;)</pre><p><strong>Output:</strong></p><pre>Fibonacci(35) = 9227465, calculated in 0.000075 seconds<br>Cache info: CacheInfo(hits=33, misses=36, maxsize=128, currsize=36)</pre><h3>4. @contextmanager: Simplify Resource Management</h3><p>Writing context managers from scratch can be verbose. With the @contextmanager decorator from contextlib, you can create them in a few lines. Below is an updated example that safely manages file operations and times code execution</p><pre>from contextlib import contextmanager<br><br>@contextmanager<br>def smart_file_manager(filename, mode):<br>    file = open(filename, mode)<br>    try:<br>        yield file<br>    finally:<br>        file.close()<br># Demonstration: Writing to a file safely<br>with smart_file_manager(&#39;sample.txt&#39;, &#39;w&#39;) as f:<br>    f.write(&quot;Hello, custom context managers!&quot;)<br>@contextmanager<br>def timer():<br>    import time<br>    start_time = time.time()<br>    yield<br>    elapsed = time.time() - start_time<br>    print(f&quot;Elapsed time: {elapsed:.6f} seconds&quot;)<br># Demonstration: Timing a computation<br>with timer():<br>    sum([i * i for i in range(1000000)])</pre><p><strong>Output:</strong></p><ul><li><strong>File Manager:</strong><br>No direct console output is produced when using smart_file_manager. However, the file sample.txt is created (or overwritten) with the content:</li></ul><pre>Hello, custom context managers!</pre><ul><li><strong>Timer:</strong><br>The timer context manager prints the elapsed time for the computation. For example, you might see an output similar to:</li></ul><pre>Elapsed time: 0.045678 seconds</pre><p><em>Note: The file manager ensures </em><em>sample.txt is properly closed, and the timer prints the elapsed time for the code block. The actual elapsed time may vary based on your system’s performance.</em></p><h3>5. @singledispatch: Elegant Function Overloading</h3><p>Python isn’t statically typed, but you can still have function behavior vary based on input types using @singledispatch. Here’s a fresh take on a formatting function that adapts its output:</p><pre>from functools import singledispatch<br>from datetime import date<br><br>@singledispatch<br>def format_value(val):<br>    return str(val)<br>@format_value.register<br>def _(val: int):<br>    return f&quot;INT: {val:+d}&quot;<br>@format_value.register<br>def _(val: float):<br>    return f&quot;FLOAT: {val:.2f}&quot;<br>@format_value.register<br>def _(val: date):<br>    return f&quot;DATE: {val.strftime(&#39;%Y-%m-%d&#39;)}&quot;<br>@format_value.register(list)<br>def _(val):<br>    return f&quot;LIST: [{&#39;, &#39;.join(format_value(item) for item in val)}]&quot;<br># Demonstration<br>formatted_results = [<br>    format_value(&quot;Hello World&quot;),<br>    format_value(42),<br>    format_value(-3.14159),<br>    format_value(date(2025, 2, 21)),<br>    format_value([1, 2.5, &quot;three&quot;])<br>]<br>for result in formatted_results:<br>    print(result)</pre><p><strong>Output:</strong></p><pre>Hello World<br>INT: +42<br>FLOAT: -3.14<br>DATE: 2025-02-21<br>LIST: [INT: +1, FLOAT: 2.50, three]</pre><h3>6. @total_ordering: Reduce Boilerplate in Comparisons</h3><p>Defining all comparison methods can be repetitive. With @total_ordering, you only need to define __eq__ and one other comparison method (like __lt__), and the rest are filled in for you. Here’s a revamped semantic versioning class:</p><pre>from functools import total_ordering<br><br>@total_ordering<br>class SemVer:<br>    def __init__(self, major, minor, patch):<br>        self.major = major<br>        self.minor = minor<br>        self.patch = patch<br>    def __eq__(self, other):<br>        if not isinstance(other, SemVer):<br>            return NotImplemented<br>        return (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)<br>    def __lt__(self, other):<br>        if not isinstance(other, SemVer):<br>            return NotImplemented<br>        return (self.major, self.minor, self.patch) &lt; (other.major, other.minor, other.patch)<br>    def __repr__(self):<br>        return f&quot;v{self.major}.{self.minor}.{self.patch}&quot;<br># Demonstration<br>versions = [<br>    SemVer(2, 0, 0),<br>    SemVer(1, 9, 5),<br>    SemVer(1, 11, 0),<br>    SemVer(2, 0, 1)<br>]<br>print(&quot;Sorted versions:&quot;, sorted(versions))<br>print(&quot;v1.9.5 &gt; v1.11.0:&quot;, SemVer(1, 9, 5) &gt; SemVer(1, 11, 0))<br>print(&quot;v2.0.0 &gt;= v2.0.0:&quot;, SemVer(2, 0, 0) &gt;= SemVer(2, 0, 0))<br>print(&quot;v2.0.1 &lt;= v2.0.0:&quot;, SemVer(2, 0, 1) &lt;= SemVer(2, 0, 0))</pre><p><strong>Output:</strong></p><pre>Sorted versions: [v1.9.5, v1.11.0, v2.0.0, v2.0.1]<br>v1.9.5 &gt; v1.11.0: False<br>v2.0.0 &gt;= v2.0.0: True<br>v2.0.1 &lt;= v2.0.0: False</pre><h3>7. @wraps: Preserve Your Function’s Identity</h3><p>When writing your own decorators, it’s important to keep the metadata (like the function’s name and docstring) intact. The @wraps decorator from functools helps you do just that. Here’s a refreshed logging decorator that wraps a simple addition function:</p><pre>import functools<br><br>def log_decorator(func):<br>    @functools.wraps(func)<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;Calling &#39;{func.__name__}&#39; with arguments: {args}, {kwargs}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;&#39;{func.__name__}&#39; returned: {result}&quot;)<br>        return result<br>    return wrapper<br>@log_decorator<br>def add_numbers(a, b):<br>    &quot;&quot;&quot;Adds two numbers together.&quot;&quot;&quot;<br>    return a + b<br># Demonstration<br>help(add_numbers)  # Shows the preserved docstring and metadata<br>print(f&quot;Function name: {add_numbers.__name__}&quot;)<br>result = add_numbers(5, 3)</pre><p><strong>Output:</strong></p><pre>Help on function add_numbers in module __main__:<br><br>add_numbers(a, b)<br>    Adds two numbers together.<br>Function name: add_numbers<br>Calling &#39;add_numbers&#39; with arguments: (5, 3), {}<br>&#39;add_numbers&#39; returned: 8</pre><h3>Wrapping Up</h3><p>Decorators are an elegant way to extend and enhance your Python code without clutter. Today, we explored:</p><ul><li><strong>@property</strong> for intuitive attribute access with built-in validation.</li><li><strong>@cached_property</strong> for caching results of heavy computations.</li><li><strong>@lru_cache</strong> to speed up recursive functions with memoization.</li><li><strong>@contextmanager</strong> for easily managing resources like files and timers.</li><li><strong>@singledispatch</strong> for clean, type-based function overloading.</li><li><strong>@total_ordering</strong> to reduce the boilerplate in comparison methods.</li><li><strong>@wraps</strong> to ensure your custom decorators preserve essential function metadata.</li></ul><p>Each decorator brings its own benefits, letting you write code that’s not only more efficient but also easier to read and maintain. What other Python decorators have you found game-changing? Drop your thoughts in the comments below!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d404d0908e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RESTful API with FastAPI: A Comprehensive Guide]]></title>
            <link>https://medium.com/@vaibhavkumar_83394/building-a-restful-api-with-fastapi-a-comprehensive-guide-82134ffdd1a2?source=rss-15f705ccb040------2</link>
            <guid isPermaLink="false">https://medium.com/p/82134ffdd1a2</guid>
            <dc:creator><![CDATA[Vaibhav Kumar]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 15:28:19 GMT</pubDate>
            <atom:updated>2024-10-10T15:28:19.939Z</atom:updated>
            <content:encoded><![CDATA[<p>In today&#39;s fast-paced web development world, creating efficient and scalable APIs is crucial. Enter FastAPI, a modern Python web framework that&#39;s been gaining tremendous popularity due to its speed, ease of use, and automatic API documentation. In this guide, we&#39;ll walk through building a robust RESTful API using FastAPI, complete with best practices and real-world examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*BIAuT7OPU0V5KFPSG4ipyw.png" /><figcaption>Python FastAPI</figcaption></figure><h3>What is FastAPI?</h3><p>FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It&#39;s designed to be easy to use, while also being fast to code and producing code that&#39;s production-ready.</p><p>Key features of FastAPI include:</p><ul><li><strong>Fast</strong>: Very high performance, on par with NodeJS and Go</li><li><strong>Fast to code</strong>: Increase the speed to develop features by about 200% to 300%</li><li><strong>Fewer bugs</strong>: Reduce about 40% of human-induced errors</li><li><strong>Intuitive</strong>: Great editor support. Auto-completion everywhere.</li><li><strong>Easy</strong>: Designed to be easy to use and learn</li><li><strong>Short</strong>: Minimize code duplication</li><li><strong>Robust</strong>: Get production-ready code</li></ul><h3>Setting Up Our Project</h3><p>First, let&#39;s install the required dependencies:</p><pre>pip install fastapi uvicorn</pre><p>Let&#39;s create a simple yet feature-rich API for managing items. Here&#39;s our complete code:</p><pre>from fastapi import FastAPI, HTTPException, Depends<br>from pydantic import BaseModel<br>from typing import List, Optional<br>import uvicorn<br>from datetime import datetime<br><br>app = FastAPI(title=&quot;Sample FastAPI Server&quot;, version=&quot;1.0.0&quot;)<br><br># Sample data store<br>items_db = []<br><br>class Item(BaseModel):<br>    id: Optional[int] = None<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    created_at: Optional[datetime] = None<br><br>class ItemUpdate(BaseModel):<br>    name: Optional[str] = None<br>    description: Optional[str] = None<br>    price: Optional[float] = None<br><br>@app.middleware(&quot;http&quot;)<br>async def log_requests(request, call_next):<br>    start_time = datetime.now()<br>    response = await call_next(request)<br>    process_time = datetime.now() - start_time<br>    print(f&quot;{request.method} {request.url} - Completed in {process_time.microseconds / 1000}ms&quot;)<br>    return response</pre><h3>Breaking Down the Code</h3><h3>1. Data Models</h3><p>We define two Pydantic models:</p><pre>class Item(BaseModel):<br>    id: Optional[int] = None<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    created_at: Optional[datetime] = None</pre><p>This model defines the structure of our items. Pydantic ensures that data validation happens automatically.</p><h3>2. CRUD Operations</h3><p>Let’s implement Create, Read, Update, and Delete operations:</p><h3>Create</h3><pre>@app.post(&quot;/items/&quot;, response_model=Item)<br>async def create_item(item: Item):<br>    item.id = len(items_db) + 1<br>    item.created_at = datetime.now()<br>    items_db.append(item)<br>    return item</pre><p>This endpoint creates a new item and adds it to our database.</p><h3>Read</h3><pre>@app.get(&quot;/items/&quot;, response_model=List[Item])<br>async def get_items(skip: int = 0, limit: int = 10):<br>    return items_db[skip : skip + limit]<br><br>@app.get(&quot;/items/{item_id}&quot;, response_model=Item)<br>async def get_item(item_id: int):<br>    if item_id &lt; 1 or item_id &gt; len(items_db):<br>        raise HTTPException(status_code=404, detail=&quot;Item not found&quot;)<br>    return items_db[item_id - 1]</pre><p>These endpoints allow fetching all items (with pagination) or a specific item by ID.</p><h3>Best Practices Implemented</h3><ol><li><strong>Type Hinting</strong>: We use Python’s type hints throughout the code, which FastAPI uses to:</li></ol><ul><li>Validate request data</li><li>Generate OpenAPI documentation</li><li>Provide better IDE support</li></ul><p><strong>2. Dependency Injection</strong>: FastAPI’s dependency injection system makes it easy to share code between endpoints:</p><pre>async def get_db():<br>    # In a real app, this would be a database connection<br>    return items_db<br><br>@app.get(&quot;/items/&quot;, response_model=List[Item])<br>async def get_items(db: list = Depends(get_db)):<br>    return db</pre><p><strong>3. Middleware for Logging</strong>: We implement middleware to log request times:</p><pre>@app.middleware(&quot;http&quot;)<br>async def log_requests(request, call_next):<br>    start_time = datetime.now()<br>    response = await call_next(request)<br>    process_time = datetime.now() - start_time<br>    print(f&quot;{request.method} {request.url} - Completed in {process_time.microseconds / 1000}ms&quot;)<br>    return response</pre><h3>Testing Our API</h3><p>To test the API, run:</p><pre>uvicorn main:app --reload</pre><p>Then open your browser to http://localhost:8000/docs to see the automatic interactive API documentation.</p><h3>Example Requests</h3><p>Here are some example curl commands to test our API:</p><ol><li>Create an item:</li></ol><pre>curl -X POST &quot;http://localhost:8000/items/&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;:&quot;Test Item&quot;,&quot;price&quot;:29.99}&#39;</pre><p>2. Get all items:</p><pre>curl &quot;http://localhost:8000/items/&quot;</pre><h3>Conclusion</h3><p>FastAPI makes it incredibly easy to build robust, high-performance APIs. With features like automatic validation, documentation, and modern Python features, it’s an excellent choice for building your next API.</p><p>Some key takeaways:</p><ul><li>FastAPI uses Python type hints for validation and documentation</li><li>It’s built on top of Starlette and Pydantic</li><li>It provides excellent performance</li><li>The automatic interactive documentation is a huge time-saver</li></ul><p>Remember, this is just scratching the surface of what FastAPI can do. For more advanced features, check out the <a href="https://fastapi.tiangolo.com/">official documentation</a>.</p><p><em>Note: This guide serves as an introduction to FastAPI. In a production environment, you’d want to add authentication, use a proper database, and implement more robust error handling.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82134ffdd1a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Tornado Webserver Simple Example]]></title>
            <link>https://medium.com/@vaibhavkumar_83394/tornado-38aeea005b09?source=rss-15f705ccb040------2</link>
            <guid isPermaLink="false">https://medium.com/p/38aeea005b09</guid>
            <dc:creator><![CDATA[Vaibhav Kumar]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 03:23:07 GMT</pubDate>
            <atom:updated>2023-01-12T03:23:47.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. It is often used for real-time applications such as chat applications, games, and other applications that require a long-lived connection to each user.</p><p>One of Tornado’s key features is its support for non-blocking, event-driven I/O, which allows it to handle thousands of concurrent connections efficiently. This makes it a good choice for building real-time web applications with high levels of concurrency.</p><p>Tornado also includes a web server, a templating engine, and other tools for building web applications. It provides a simple, easy-to-use API for handling HTTP requests, as well as support for common web protocols such as WebSockets.</p><p>Tornado can be used to build a wide range of different types of web applications, including traditional server-rendered web applications, as well as web APIs and real-time web services. You can also use it as an extension or building block to build more complex systems.</p><p>Here is a example of a simple Tornado Web server</p><pre>import tornado.ioloop<br>import tornado.web<br><br>class MainHandler(tornado.web.RequestHandler):<br>    def get(self):<br>        self.write(&quot;Hello, World!&quot;)<br><br>def make_app():<br>    return tornado.web.Application([<br>        (r&quot;/&quot;, MainHandler),<br>    ])<br><br>if __name__ == &quot;__main__&quot;:<br>    app = make_app()<br>    app.listen(8888)<br>    tornado.ioloop.IOLoop.current().start()</pre><p>This example creates a Tornado web server that listens on port 8888 and handles a single route, the root (“/”) path. When a client navigates to that path in their web browser, the server will respond with the text “Hello, World!”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38aeea005b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>