<?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 Heval Hazal Kurt on Medium]]></title>
        <description><![CDATA[Stories by Heval Hazal Kurt on Medium]]></description>
        <link>https://medium.com/@hevalhazalkurt?source=rss-8d37d1c078f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JYxNilo6VBzWreImAYv_Tw.png</url>
            <title>Stories by Heval Hazal Kurt on Medium</title>
            <link>https://medium.com/@hevalhazalkurt?source=rss-8d37d1c078f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:00:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hevalhazalkurt/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[Encapsulation and Domain-Driven Design in Python Projects]]></title>
            <link>https://python.plainenglish.io/encapsulation-and-domain-driven-design-in-python-projects-b8a24ceb7e48?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8a24ceb7e48</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 17:38:52 GMT</pubDate>
            <atom:updated>2026-09-09T15:30:59.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7IJGv-vR1yzMrniNon8iA.jpeg" /></figure><p>When you hear the word “encapsulation”, you might think of private variables or hiding attributes in classes. And that’s partly true. But in real-world Python projects, especially large backend systems, encapsulation plays a much deeper role. It helps us design systems that are easier to change, test, and understand. And when you combine it with Domain-Driven Design (DDD) principles, you can build robust, maintainable applications that actually model the complexity of your business logic.</p><p>This blog post will walk you through the concept of encapsulation in Python, show how it applies in Domain-Driven Design, and give you practical, examples from backend systems.</p><h3>What Is Encapsulation, Really?</h3><p>Encapsulation is about hiding the internal state and requiring all interactions to go through well-defined interfaces. In Python, we can’t truly make things private like in Java or C++. But we can mark something as “private by convention” using a leading underscore (_) or make it strongly suggested private with double underscore name mangling (__).</p><p>Let’s take a look at a basic example →</p><pre>class User:<br>    def __init__(self, username, password):<br>        self.username = username<br>        self.__password = password  # private<br><br>    def check_password(self, input_password):<br>        return self.__password == input_password</pre><p>In this example, __password is intended to be private. You don&#39;t want other parts of the system to modify or read it directly. Instead, you provide a method check_password() that safely compares a given input. This keeps your internal logic safe from accidental tampering and provides a clear interface for how other code should interact with the object.</p><p>But what about a real-world app?</p><h3>Encapsulation in Backend Services</h3><p>In backend projects, we encapsulate not just data, but business rules, invariants, and logic flows. Here’s a more realistic example: managing a user account.</p><pre>class User:<br>    def __init__(self, username):<br>        self.username = username<br>        self.__is_active = False<br><br>    def activate(self):<br>        self.__is_active = True<br><br>    def deactivate(self):<br>        self.__is_active = False<br><br>    def is_active(self):<br>        return self.__is_active</pre><p>In this version, instead of letting external code flip the is_active flag directly, we enforce all state changes through methods. This gives us the power to later add logic like sending an email when a user is activated or logging the action. The actual boolean flag is protected inside the object, ensuring consistency and centralizing rule enforcement.</p><h3>Introducing Domain-Driven Design (DDD)</h3><p>DDD is a design philosophy that focuses on modeling the real-world domain in code. It encourages dividing your codebase into:</p><ul><li><strong>Entities</strong>: objects with a unique identity and lifecycle like User, Order</li><li><strong>Value Objects</strong>: immutable objects with no identity like Money, DateRange</li><li><strong>Aggregates</strong>: clusters of objects treated as a unit</li><li><strong>Repositories</strong>: interfaces for accessing aggregates</li><li><strong>Services</strong>: operations that don’t naturally belong to a specific entity</li></ul><p>Encapsulation in DDD means: hide internal state and enforce all rules through methods on the domain object.</p><h3>Example: An Order System with Encapsulation</h3><p>Let’s model an order that has line items, a status, and a business rule: you can only cancel if it’s not shipped.</p><pre>class Order:<br>    def __init__(self, order_id):<br>        self.order_id = order_id<br>        self.__items = []<br>        self.__status = &quot;draft&quot;<br><br>    def add_item(self, item):<br>        if self.__status != &quot;draft&quot;:<br>            raise Exception(&quot;Can&#39;t add items after order is confirmed&quot;)<br>        self.__items.append(item)<br><br>    def confirm(self):<br>        if not self.__items:<br>            raise Exception(&quot;Can&#39;t confirm empty order&quot;)<br>        self.__status = &quot;confirmed&quot;<br><br>    def cancel(self):<br>        if self.__status == &quot;shipped&quot;:<br>            raise Exception(&quot;Can&#39;t cancel a shipped order&quot;)<br>        self.__status = &quot;canceled&quot;<br><br>    def ship(self):<br>        if self.__status != &quot;confirmed&quot;:<br>            raise Exception(&quot;Can&#39;t ship unless confirmed&quot;)<br>        self.__status = &quot;shipped&quot;<br><br>    def status(self):<br>        return self.__status</pre><p>Why this is good encapsulation</p><ul><li>Business rules are enforced inside the object.</li><li>No external code can make the order “shipped” without going through the ship() method.</li><li>Side effects like logging or emails can be added to the cancel() method, and all callers benefit.</li></ul><h3>Value Object: Money</h3><p>Let’s say you want to represent prices safely.</p><pre>class Money:<br>    def __init__(self, amount, currency):<br>        if amount &lt; 0:<br>            raise ValueError(&quot;Amount can&#39;t be negative&quot;)<br>        self.amount = amount<br>        self.currency = currency<br><br>    def __add__(self, other):<br>        if self.currency != other.currency:<br>            raise ValueError(&quot;Currency mismatch&quot;)<br>        return Money(self.amount + other.amount, self.currency)</pre><p>This class is a value object. It has no identity, and it’s defined only by its content. You use Money instead of raw floats or integers to make sure every piece of price-related logic goes through this safe structure. For instance, you can prevent someone from accidentally mixing EUR and USD values, or from passing a negative price into your system.</p><h3>Advanced Pattern: Aggregate Roots and Invariants</h3><p>In DDD, an aggregate root is the main entity that guards the consistency of related objects. Let’s extend our Order to also manage shipments. Instead of letting another class touch shipment state, the Order itself enforces the rules.</p><pre>class Shipment:<br>    def __init__(self):<br>        self.__shipped = False<br><br>    def mark_shipped(self):<br>        self.__shipped = True<br><br>    def is_shipped(self):<br>        return self.__shipped<br><br><br>class Order:<br>    def __init__(self, order_id):<br>        self.order_id = order_id<br>        self.__status = &quot;draft&quot;<br>        self.__shipment = Shipment()<br><br>    def ship(self):<br>        if self.__status != &quot;confirmed&quot;:<br>            raise Exception(&quot;Can&#39;t ship unless confirmed&quot;)<br>        self.__shipment.mark_shipped()<br>        self.__status = &quot;shipped&quot;</pre><p>Here, the Shipment class is completely hidden inside the Order object. External callers can&#39;t directly call mark_shipped() on the shipment. This means the only way to change shipment state is by calling Order.ship(). That way, we ensure the order&#39;s status and the shipment&#39;s status stay in sync.</p><h3>Common Mistakes When Encapsulating</h3><ul><li>Making fields public “just to make testing easier”</li><li>Allowing direct database models like SQLAlchemy to leak into business logic</li><li>Writing services that manipulate raw dicts instead of rich objects</li></ul><p>Encapsulation isn’t just a language feature, it’s a discipline.</p><h3>Takeaways</h3><ul><li>Encapsulation in Python goes beyond hiding variables; it’s about protecting your domain logic.</li><li>Domain-Driven Design gives you a structure to group and encapsulate logic meaningfully.</li><li>In real-world backends, encapsulated entities and aggregates make your codebase more testable and maintainable.</li></ul><p>If you’re working on a system that models real business processes, encapsulation + DDD is your best friend.</p><p>The original post is <a href="https://hevalhazalkurt.com/blog/encapsulation-and-domain-driven-design-in-python-projects/">here</a>.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8a24ceb7e48" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/encapsulation-and-domain-driven-design-in-python-projects-b8a24ceb7e48">Encapsulation and Domain-Driven Design in Python Projects</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Composition Beats Inheritance in Large-Scale Python Systems]]></title>
            <link>https://python.plainenglish.io/why-composition-beats-inheritance-in-large-scale-python-systems-45f9fdc90370?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f9fdc90370</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 17:59:10 GMT</pubDate>
            <atom:updated>2025-12-09T13:43:11.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHVmzftRbcl-pmQ62ErHoQ.jpeg" /></figure><p>When you start out learning object-oriented programming (OOP) in Python, inheritance feels like the obvious way to reuse code. You build a base class, extend it, and reuse its behavior. But as your software grows, you might start noticing that inheritance introduces tight coupling, rigid structures, and eventually… a mess.</p><p>This post is about why composition is often a better choice than inheritance in large-scale Python systems, especially when you’re building backend applications. We’ll start from the basics, then go into real-life backend scenarios to show how composition can help you write cleaner, more maintainable code.</p><h3>Inheritance vs Composition</h3><p><strong>Inheritance</strong> means creating a new class that is a type of another class. It forms an “is-a” relationship. The child class (subclass) automatically gets the properties and methods of the parent (base) class. This is great when the subclass truly is a specialized form of the parent.</p><pre>class Animal:<br>    def speak(self):<br>        return &quot;Some sound&quot;<br><br>class Dog(Animal):<br>    def speak(self):<br>        return &quot;Woof!&quot;</pre><p>Here, Dog is an Animal, so it makes sense to inherit. But if you start inheriting just to reuse speak(), that&#39;s a red flag, you&#39;re misusing inheritance.</p><p><strong>Composition</strong>, on the other hand, means building a class using other classes often by passing them in as attributes. It forms a “has-a” relationship. One class delegates behavior to another, which makes the structure more flexible and modular.</p><pre>class Engine:<br>    def start(self):<br>        return &quot;Engine started&quot;<br><br>class Car:<br>    def __init__(self, engine):<br>        self.engine = engine<br><br>    def start(self):<br>        return self.engine.start()</pre><p>Here, Car has an Engine, and it uses the engine&#39;s behavior without being tightly bound to its implementation. This makes testing, swapping, or extending Engine behavior much easier.</p><p>To sum it up:</p><ul><li>Use <strong>inheritance</strong> when you have a clear hierarchical relationship.</li><li>Use <strong>composition</strong> when you want flexibility, testability, and better separation of concerns.</li></ul><h3>The Problems with Inheritance in Big Codebases</h3><p>In small systems, inheritance can work fine. But once you scale up, it starts to cause trouble:</p><h4>1. Tight Coupling</h4><p>Child classes depend on the structure of the parent. If you change the base class, you risk breaking subclasses.</p><h4>2. Inheritance Hierarchies Get Deep and Confusing</h4><p>When you have a base class, a child class, a grandchild class… it’s hard to track where methods are coming from.</p><h4>3. Inheritance Isn’t Flexible</h4><p>What if you need to reuse the same behavior in two unrelated classes? Inheritance can’t help without breaking the “is-a” rule.</p><h4>4. Testing Becomes Harder</h4><p>When behavior is inherited from many levels up, writing isolated unit tests becomes a pain.</p><h3>Composition to the Rescue</h3><p>With composition, you build classes that contain instances of other classes. This way, your classes are like Lego blocks: reusable, testable, and loosely coupled. Let’s walk through some backend scenarios where composition shines.</p><h3>Scenario 1: Injecting Services into API Endpoints</h3><p>When building real-world APIs, for example with FastAPI or Flask, you often need to integrate services like email delivery, logging, analytics, or third-party APIs. A common mistake is to tightly bind these services into the route or controller logic, or worse, to subclass everything in an attempt to “reuse” behavior. That’s where composition becomes a huge win.</p><p>Let’s say your API should send a welcome email when a new user signs up. You might be tempted to create a BaseSignupHandler with a send_email method, and then subclass it. But that approach hardwires the behavior and makes testing or swapping the email logic a pain.</p><p>Instead, you can define a dedicated service class:</p><pre>class EmailService:<br>    def send(self, to, subject, body):<br>        # Send email logic here<br>        print(f&quot;Sending to {to}: {subject}&quot;)<br><br><br>class UserSignupHandler:<br>    def __init__(self, email_service: EmailService):<br>        self.email_service = email_service<br><br>    def signup(self, user_email):<br>        # Create user...<br>        self.email_service.send(<br>            to=user_email,<br>            subject=&quot;Welcome!&quot;,<br>            body=&quot;Thanks for signing up.&quot;<br>        )</pre><p>This gives you several advantages:</p><p><strong>Testability</strong>: You can mock or stub the email service without changing UserSignupHandler:</p><pre>class MockEmailService:<br>    def send(self, to, subject, body):<br>        print(&quot;Mock send&quot;)</pre><p>Now your tests can look like:</p><pre>handler = UserSignupHandler(MockEmailService())<br>handler.signup(&quot;test@example.com&quot;)</pre><p><strong>Flexibility</strong>: Tomorrow you may want to send Slack notifications or SMS instead of email. With composition, you can simply replace EmailService with another implementation. No inheritance gymnastics required.</p><p><strong>Decoupling</strong>: UserSignupHandler doesn&#39;t care how the message is sent. It only knows it can delegate to the service object. This keeps business logic clean and isolated.</p><p>In backend systems, you’ll commonly inject:</p><ul><li>Database repositories</li><li>Messaging clients like Kafka, RabbitMQ</li><li>External API clients like Stripe, AWS SDKs</li><li>Logger or metrics providers</li></ul><p>Each of these is a perfect candidate for composition.</p><p>By embracing composition for service injection, you’re not only making your code easier to maintain and test. You’re also aligning with modern software engineering practices like dependency injection and separation of concerns.</p><p>Say you’re writing a FastAPI app that has to send emails. Instead of subclassing some EmailSenderBase, you use composition:</p><h3>Scenario 2: Payments with Strategy Pattern via Composition</h3><p>Let’s say your app supports multiple payment gateways:</p><pre>class StripePayment:<br>    def charge(self, amount):<br>        print(f&quot;Charging ${amount} using Stripe&quot;)<br><br>class PaypalPayment:<br>    def charge(self, amount):<br>        print(f&quot;Charging ${amount} using PayPal&quot;)<br><br><br>class PaymentProcessor:<br>    def __init__(self, strategy):<br>        self.strategy = strategy<br><br>    def pay(self, amount):<br>        return self.strategy.charge(amount)</pre><p>You can switch strategies at runtime:</p><pre>processor = PaymentProcessor(StripePayment())<br>processor.pay(100)  # Uses Stripe<br><br>processor.strategy = PaypalPayment()<br>processor.pay(200)  # Now uses PayPal</pre><p>This level of flexibility is very hard to achieve with inheritance.</p><h3>Scenario 3: Repository Pattern with Swappable Storage</h3><p>Let’s say you want to store user data, but don’t want your business logic to care whether it’s PostgreSQL or Redis.</p><pre>class PostgresUserRepo:<br>    def get_user(self, user_id):<br>        return {&quot;id&quot;: user_id, &quot;name&quot;: &quot;Postgres User&quot;}<br><br><br>class RedisUserRepo:<br>    def get_user(self, user_id):<br>        return {&quot;id&quot;: user_id, &quot;name&quot;: &quot;Redis Cached User&quot;}<br><br><br>class UserService:<br>    def __init__(self, user_repo):<br>        self.user_repo = user_repo<br>    def load_user(self, user_id):<br>        return self.user_repo.get_user(user_id)</pre><p>In tests, you might use an in-memory version:</p><pre>class InMemoryUserRepo:<br>    def get_user(self, user_id):<br>        return {&quot;id&quot;: user_id, &quot;name&quot;: &quot;Test User&quot;}</pre><h3>Advantages of Composition in Production Code</h3><p><strong>Loose Coupling</strong></p><p>You can change internal parts without touching other parts of the system.</p><p><strong>Easier Testing</strong></p><p>Just inject mock or fake objects.</p><p><strong>More Reuse</strong></p><p>Composable behaviors can be shared across unrelated classes.</p><p><strong>Better Code Organization</strong></p><p>Each class has one responsibility. You don’t need to dig through long inheritance trees.</p><p><strong>Dynamic Behavior</strong></p><p>You can change or decorate behavior at runtime.</p><h3>So..</h3><p>In short, inheritance is great when there is a true “is-a” relationship. But in real-world backend code, that’s rare. What you really need is flexible, maintainable, and testable code. That’s where composition shines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f9fdc90370" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/why-composition-beats-inheritance-in-large-scale-python-systems-45f9fdc90370">Why Composition Beats Inheritance in Large-Scale Python Systems</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Retryable Asynchronous APIs Using functools.partial and Custom Decorators]]></title>
            <link>https://python.plainenglish.io/designing-retryable-asynchronous-apis-using-functools-partial-and-custom-decorators-d29b1794f2c1?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d29b1794f2c1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 15:56:42 GMT</pubDate>
            <atom:updated>2025-11-08T08:09:31.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC7aC_5eawJ-nPjNVnwYUA.jpeg" /></figure><p>In the world of building reliable backend systems, things break. APIs timeout, services become temporarily unavailable, and database queries may fail due to load. One common and essential solution to this is a retry mechanism, a pattern that automatically re-attempts a failed operation after a delay.</p><p>In this blog post, we’re going to explore how to build retryable asynchronous APIs using Python. We’ll walk through how to use functools.partial in combination with custom async decorators to create flexible, reusable retry logic. Let’s dive in.</p><h3>Why Retry Logic Matters</h3><p>Let’s say you’re calling an external payment API or fetching analytics from a third-party provider. These services might fail intermittently. If you just let those exceptions bubble up, you’re either forcing your users to refresh the page or retry manually, which is a bad experience.</p><p>A retry decorator can give your system some resilience:</p><ul><li>Try again automatically if an exception occurs.</li><li>Add delay, jitter, or exponential backoff.</li><li>Log what failed and when it’s trying again.</li></ul><h3>Starting Simple: Retry with Async Function</h3><p>Let’s start with a basic version of an async retry decorator:</p><pre>import asyncio<br>import random<br>from functools import partial<br><br><br>async def retry(f, tries=3, delay=1):<br>    for attempt in range(tries):<br>        try:<br>            return await f()<br>        except Exception as e:<br>            if attempt == tries - 1:<br>                raise<br><br>            print(f&quot;Attempt {attempt+1} failed: {e}. Retrying in {delay}s...&quot;)<br>            await asyncio.sleep(delay)</pre><p>This works if you pass an async function with no arguments. But that’s a big limitation. What if you want to pass arguments to the function?</p><h3>Pre-binding Function Arguments with functools.partial</h3><p>The functools.partial tool allows you to bind arguments to a function in advance.</p><pre>from functools import partial<br><br>async def greet(name):<br>    print(f&quot;Hello, {name}!&quot;)<br><br># Create a version of greet where name is pre-filled<br>partial_greet = partial(greet, &quot;Alice&quot;)<br>await partial_greet()  # Hello, Alice!</pre><p>This is exactly what we need to make our retry logic generic. We’ll use partial to wrap any function and its arguments into a single callable.</p><h3>Making a Reusable Retry Decorator</h3><p>Now we’ll build a proper decorator that supports:</p><ul><li>Any async function with arguments</li><li>Customizable retry parameters (delay, tries, backoff, jitter)</li></ul><pre>from decorator import decorator  <br><br>@decorator<br>async def retry_decorator(f, *fargs, tries=3, delay=1, backoff=1, jitter=0, **fkwargs):<br>    _tries, _delay = tries, delay<br>    wrapped = partial(f, *fargs, **fkwargs)<br>    while _tries:<br>        try:<br>            return await wrapped()<br>        except Exception as e:<br>            _tries -= 1<br>            if not _tries:<br>                raise<br><br>            print(f&quot;Retrying after error: {e}. Next attempt in {_delay}s&quot;)<br>            await asyncio.sleep(_delay + random.uniform(0, jitter))<br>            _delay *= backoff</pre><p>Now, use it like this:</p><pre>@retry_decorator(tries=5, delay=2, backoff=2, jitter=1)<br>async def fetch_remote_data():<br>    # Simulate a flaky operation<br>    if random.random() &lt; 0.7:<br>        raise Exception(&quot;Temporary failure&quot;)<br>    return {&quot;status&quot;: &quot;success&quot;}</pre><h3>Wrapping a DB Query or HTTP Call</h3><p>Imagine you’re querying a third-party analytics service:</p><pre>@retry_decorator(tries=4, delay=1, backoff=2, jitter=0.5)<br>async def fetch_analytics(account_id):<br>    async with httpx.AsyncClient() as client:<br>        response = await client.get(f&quot;&lt;https://api.example.com/data/{account_id}&gt;&quot;)<br>        response.raise_for_status()<br>        return response.json()</pre><p>Even if the service fails a couple of times, your user never notices. It retries silently under the hood.</p><h3>How partial Helps</h3><p>The magic of partial() is that we don’t have to worry about how many arguments the wrapped function has or what they are. We just pass them into partial, and it gives us a single callable to run in our retry loop.</p><p>This makes the decorator very generic and safe to use across different parts of the codebase.</p><h3>A Few Use Cases</h3><ul><li><strong>Logging</strong>: Pass a logger to log retries and errors.</li><li><strong>Custom Exceptions</strong>: Only retry certain errors (e.g., timeouts).</li><li><strong>Max Delay</strong>: Clamp exponential backoff to avoid long waits.</li></ul><pre>@retry_decorator(tries=5, delay=1, backoff=2, jitter=(0.5, 1.5))<br>async def get_data():<br>    # maybe fails due to network</pre><p>For jitter, you can pass a range tuple. The decorator could support random.uniform(min, max).</p><h3>When to Use and When Not To</h3><p>Use retry decorators for:</p><ul><li>External HTTP APIs</li><li>Cache misses + refresh logic</li><li>Transient DB/network errors</li></ul><p>Don’t use them when:</p><ul><li>The failure is a programming bug</li><li>You expect high throughput because retrying can increase load</li><li>You want transactional guarantees like DB write consistency</li></ul><h3>Wrap-up</h3><p>Retry logic is one of those things that every backend system needs, but it’s easy to overcomplicate. Using functools.partial lets you build flexible decorators that work with any async function, no matter its signature. By combining it with a custom async decorator, you can write production-grade retry logic that’s reusable, testable, and easy to read.</p><p>The original post is <a href="https://hevalhazalkurt.com/blog/designing-retryable-asynchronous-apis-using-functoolspartial-and-custom-decorators/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d29b1794f2c1" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/designing-retryable-asynchronous-apis-using-functools-partial-and-custom-decorators-d29b1794f2c1">Designing Retryable Asynchronous APIs Using functools.partial and Custom Decorators</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Scope Management in Modular Python Design]]></title>
            <link>https://python.plainenglish.io/the-art-of-scope-management-in-modular-python-design-34b194e29b06?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b194e29b06</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 17:15:36 GMT</pubDate>
            <atom:updated>2025-10-29T14:35:59.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrmcBLQw1oxZSawt4S57hw.jpeg" /></figure><p>When you work on a large Python codebase, especially in backend projects using Django, FastAPI, or Flask, you probably see the chaos that poor scope management can cause. From mysterious bugs and unpredictable state to namespace collisions and tangled dependencies, things get messy fast when variable scope isn’t handled with care.</p><h3>What Is “Scope” in Python?</h3><p>In simple terms, scope is where a variable can be seen or used. For example:</p><pre>def greet():<br>    name = &quot;Alice&quot;<br>    print(name)<br><br>print(name)  # NameError: name is not defined</pre><p>Here, name is only visible inside the greet() function. That’s its scope. Python uses something called the LEGB rule to decide how it looks for variables.</p><h3>The LEGB Rule: Python’s Scope Lookup Chain</h3><p>This rule stands for:</p><ul><li><strong>L</strong>ocal — variables defined inside a function.</li><li><strong>E</strong>nclosing — variables in parent functions when functions are nested.</li><li><strong>G</strong>lobal — variables defined at the module level.</li><li><strong>B</strong>uilt-in — stuff that comes with Python, like len, print, range.</li></ul><p>When you reference a variable, Python starts at the innermost scope and moves outward until it finds it. Here’s a quick example:</p><pre>x = &quot;global&quot;<br><br>def outer():<br>    x = &quot;enclosing&quot;<br><br>    def inner():<br>        x = &quot;local&quot;<br>        print(x)<br>    inner()<br><br>outer()  # prints &quot;local&quot;</pre><p>If you remove x = &quot;local&quot; from inner(), Python prints &quot;enclosing&quot; — and if that’s gone too, it prints &quot;global&quot;. This rule is simple… until your app grows.</p><h3>Why Scope Matters</h3><p>Let’s say you’re building a backend service with FastAPI, and you start breaking your code into modules:</p><pre>/project<br>  ├── main.py<br>  ├── database.py<br>  ├── models.py<br>  ├── routers/<br>  │     └── user.py</pre><p>If you don’t manage scope carefully, you’ll run into things like:</p><ul><li>Circular imports</li><li>Unpredictable globals</li><li>Variables that vanish or leak</li><li>Hard-to-debug state in production</li></ul><p>Let’s see how you can manage scope cleanly.</p><h3>Rule 1: Keep Your Global Scope Clean</h3><p>Your main.py is your entry point. It should only:</p><ul><li>Start the app</li><li>Include global configuration (maybe via os.environ)</li><li>Register routers and services</li></ul><p><strong>Good:</strong></p><pre># main.py<br>from fastapi import FastAPI<br>from routers import user<br><br>app = FastAPI()<br>app.include_router(user.router)</pre><p><strong>Bad:</strong></p><pre># main.py<br>db_connection = connect_to_db()<br>SOME_MAGIC_GLOBAL_STATE = {}<br><br># Used all over your app without structure</pre><p>Why it’s bad: When you use global mutable objects, things can go wrong in concurrency, testing, or scaling. They also make your app harder to test.</p><p><strong>Instead</strong>: Pass state as arguments or use dependency injection, FastAPI supports this.</p><h3>Use Module Scope for Reusability</h3><p>Imagine you have a database.py file that sets up your DB engine:</p><pre># database.py<br>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker<br><br>engine = create_engine(&quot;sqlite:///example.db&quot;)<br>SessionLocal = sessionmaker(bind=engine)</pre><p>This is good use of module scope. When you import SessionLocal, it’s consistent and controlled.</p><p>Example:</p><pre># routers/user.py<br>from fastapi import Depends<br>from sqlalchemy.orm import Session<br>from database import SessionLocal<br><br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()<br><br><br>@router.get(&quot;/users/&quot;)<br>def read_users(db: Session = Depends(get_db)):<br>    return db.query(User).all()</pre><p>Notice how we don’t expose too much. We don’t let engine float around everywhere. SessionLocal is the scoped, reusable object.</p><h3>Avoid Import-Time Side Effects</h3><p>A common mistake:</p><pre># models.py<br>from database import SessionLocal<br><br>SessionLocal().execute(&quot;DROP TABLE users;&quot;)  # this runs on import</pre><p>Importing a module should not perform dangerous actions. That’s a scope + timing issue.</p><p>Instead:</p><ul><li>Keep logic inside functions.</li><li>Only run them when explicitly called.</li><li>Avoid code at the top level that mutates or acts.</li></ul><h3>Advanced Scope Patterns for Large Projects</h3><p>Let’s get into deeper waters.</p><h3>1. Dependency Injection with Scope Control</h3><p>FastAPI lets you use function-level scope to inject services:</p><pre>def get_current_user(token: str = Depends(oauth2_scheme)):<br>    user = decode_token(token)<br>    return user</pre><p>This is better than making current_user a global variable. It’s safer, more testable, and better scoped.</p><h3>Using Classes to Encapsulate State</h3><p>Sometimes, you need state. Don’t abuse globals, use classes:</p><pre># services/user_service.py<br>class UserService:<br>    def __init__(self, db):<br>        self.db = db<br><br>    def get_user(self, user_id):<br>        return self.db.query(User).filter_by(id=user_id).first()</pre><p>In your endpoint:</p><pre>@router.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int, db: Session = Depends(get_db)):<br>    service = UserService(db)<br>    return service.get_user(user_id)</pre><p>Here, db is passed down cleanly, no surprises, no globals.</p><h3>Factory Functions and Closures for Configurable Behavior</h3><p>Sometimes closures help with scope:</p><pre>def make_greeting(prefix):<br>    def greet(name):<br>        return f&quot;{prefix}, {name}!&quot;<br>    return greet<br><br><br>hello = make_greeting(&quot;Hello&quot;)<br>print(hello(&quot;Alice&quot;))  # Hello, Alice!</pre><p>Use this in backends to build things like custom validators, filters, or pipelines with stored context.</p><h3>Clean Scope = Clean Code</h3><p>To wrap it up, good scope management makes your Python code:</p><ul><li>Easier to test</li><li>Easier to maintain</li><li>Safer in production</li><li>Faster to understand</li></ul><p>The original post is <a href="https://hevalhazalkurt.com/blog/the-art-of-scope-management-in-modular-python-design/">here</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b194e29b06" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/the-art-of-scope-management-in-modular-python-design-34b194e29b06">The Art of Scope Management in Modular Python Design</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slotted classes with __slots__ in Python]]></title>
            <link>https://python.plainenglish.io/slotted-classes-with-slots-in-python-9450ecc54d23?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9450ecc54d23</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 18:01:40 GMT</pubDate>
            <atom:updated>2025-10-02T04:12:02.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-XKmvu8OOs6aPtGt41fPA.jpeg" /></figure><p>When we build backend systems in Python, performance isn’t always our first concern. But sometimes, especially when you have thousands or even millions of objects in memory like API response models, simulation agents, or data processing pipelines, memory usage and speed start to matter. One of the lesser-known Python features that can help in such cases is __slots__.</p><p>In this blog, we’ll explore __slots__ from beginner level to more advanced use cases, with clear examples and backend-oriented use cases.</p><h3>What is __slots__?</h3><p>In Python, every object by default stores its attributes in a special dictionary called __dict__. This dictionary allows us to dynamically add, remove, or modify attributes at runtime.</p><pre>class User:<br>    def __init__(self, name, email):<br>        self.name = name<br>        self.email = email<br><br><br>u = User(&quot;Alice&quot;, &quot;alice@example.com&quot;)<br>u.age = 30  # works just fine</pre><p>But this flexibility comes at a cost. Every instance carries a dynamic dictionary, which adds memory overhead and makes attribute access a tiny bit slower. That’s where __slots__ comes in. __slots__ lets you define a fixed set of attributes for a class. When used, Python doesn’t create a __dict__ for each instance, reducing memory usage.</p><pre>class SlimUser:<br>    __slots__ = [&#39;name&#39;, &#39;email&#39;]<br><br>    def __init__(self, name, email):<br>        self.name = name<br>        self.email = email</pre><p>Now, trying to add a new attribute:</p><pre>s = SlimUser(&quot;Bob&quot;, &quot;bob@example.com&quot;)<br>s.age = 25  # AttributeError: &#39;SlimUser&#39; object has no attribute &#39;age&#39;</pre><h3>Why Should You Care?</h3><p>In backend systems, we often work with many lightweight objects:</p><ul><li>API response models</li><li>Background job data containers</li><li>DTOs (Data Transfer Objects)</li><li>Caching layers</li></ul><p>In these cases, saving even a few bytes per object can scale into megabytes or more.</p><h3>Example: API Models</h3><pre>class Product:<br>    def __init__(self, id, name, price):<br>        self.id = id<br>        self.name = name<br>        self.price = price</pre><p>Suppose you’re loading 1 million Product instances into memory for caching. Using __slots__:</p><pre>class SlimProduct:<br>    __slots__ = [&#39;id&#39;, &#39;name&#39;, &#39;price&#39;]<br><br>    def __init__(self, id, name, price):<br>        self.id = id<br>        self.name = name<br>        self.price = price</pre><p>Using sys.getsizeof() won&#39;t show the full memory benefit because it only shows shallow size, but if you compare .__dict__ and .__slots__ attributes or use tools like pympler or tracemalloc will show significant reduction when objects are deeply nested.</p><h3>How __slots__ Works Under the Hood</h3><p>When you use __slots__, Python internally creates a more static structure like a C struct instead of a dynamic dictionary. It uses descriptors and a slot table to manage attribute access.</p><p>Benefits:</p><ul><li>Reduced memory usage per object</li><li>Slightly faster attribute access</li><li>Prevents accidental addition of unexpected attributes</li></ul><p>Drawbacks:</p><ul><li>No dynamic attribute assignment</li><li>Can’t easily use pickling without extra steps</li><li>Subclassing can be tricky (see below)</li></ul><h3>Combining __slots__ and Inheritance</h3><p>Slotted classes can’t be freely combined like regular ones. If you subclass a slotted class, you need to define __slots__ again even if it&#39;s empty.</p><pre>class Base:<br>    __slots__ = [&#39;id&#39;]<br><br><br>class Child(Base):<br>    __slots__ = [&#39;name&#39;]</pre><p>If you forget to redefine __slots__, Python will revert to using __dict__ in the subclass.</p><p>You can also include __dict__ in the slots explicitly if you want partial flexibility:</p><pre>class PartiallyDynamic:<br>    __slots__ = [&#39;id&#39;, &#39;__dict__&#39;]</pre><h3>@dataclass with slots=True</h3><p>Python 3.10+ allows using __slots__ automatically with dataclasses:</p><pre>from dataclasses import dataclass<br><br>@dataclass(slots=True)<br>class Product:<br>    id: int<br>    name: str<br>    price: float</pre><p>This is much cleaner and combines the benefits of dataclasses like auto-generated __init__, __repr__, etc. with memory savings.</p><h3>Caching API Responses</h3><p>Suppose you’re building a high-throughput API that returns lots of small JSON records from Redis or a database. Each record is parsed into a Python object.</p><pre>class CachedItem:<br>    __slots__ = [&#39;id&#39;, &#39;category&#39;, &#39;value&#39;]<br><br>    def __init__(self, id, category, value):<br>        self.id = id<br>        self.category = category<br>        self.value = value</pre><p>This keeps your memory usage lean, especially if you’re storing thousands of these in memory. You can even combine __slots__ with __slots__ + property to make fields read-only:</p><pre>class ImmutableItem:<br>    __slots__ = [&#39;_id&#39;]<br><br>    def __init__(self, id):<br>        self._id = id<br><br>    @property<br>    def id(self):<br>        return self._id</pre><h3>When Not to Use __slots__</h3><p>Don’t use __slots__ if:</p><ul><li>You rely on libraries that dynamically add attributes like some ORMs or serializers</li><li>You need full pickling support</li><li>You’re writing code that heavily depends on __dict__ introspection</li></ul><p>It’s a tool, not a silver bullet. Use it when profiling shows memory usage is actually a concern.</p><h3>Summary</h3><p>__slots__ is a powerful but often overlooked feature in Python that can help reduce memory usage and improve attribute access performance in certain use cases. Especially in backend systems where you handle lots of structured but repetitive objects like response models or cached entities, slotted classes can provide measurable performance benefits.</p><p>Use them with care, test them in your architecture, and always validate with profiling tools before optimizing prematurely.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9450ecc54d23" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/slotted-classes-with-slots-in-python-9450ecc54d23">Slotted classes with __slots__ in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the GIL Affects Real Python Workloads]]></title>
            <link>https://hevalhazalkurt.medium.com/how-the-gil-affects-real-python-workloads-265408412798?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/265408412798</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 15:55:33 GMT</pubDate>
            <atom:updated>2025-09-25T15:55:33.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0A41pshOl29V8VcIhleTA.jpeg" /></figure><p>If you’ve ever tried to speed up your Python application by adding threads, only to see… nothing change. Well, welcome to the world of the Global Interpreter Lock (GIL). In this post, we’re going to break down how the GIL affects concurrency performance, especially in real-life backend workloads.</p><h3>What’s the GIL?</h3><p>The Global Interpreter Lock is a mutex that prevents multiple native threads from executing Python bytecodes at once in the CPython interpreter. It’s like a nightclub bouncer: only one thread can enter the Python bytecode dancefloor at a time even if there’s space for more. This means that:</p><ul><li>Threads in Python aren’t truly concurrent when doing CPU work.</li><li>You don’t get free performance gains just by spawning threads for heavy computation.</li><li>I/O-heavy code can still benefit from threading, because the GIL is released during I/O.</li></ul><h3>CPU-Bound vs I/O-Bound: Why It Matters</h3><p>Let’s define these first:</p><ul><li>CPU-bound: Code that mainly uses CPU cycles like data crunching, image processing.</li><li>I/O-bound: Code that mostly waits like network requests, database calls, file I/O.</li></ul><p>Why does this matter? Because the GIL hurts you most when your code is CPU-bound. That’s when threads fight over the lock. But for I/O-bound code, threads take turns nicely, because the GIL is released during blocking I/O.</p><h3>Example #1: CPU-Bound Task (With Threads)</h3><p>Let’s simulate a CPU-heavy workload using threads:</p><pre>import threading<br>import time<br><br>COUNT = 50_000_000<br>def cpu_heavy():<br>    x = 0<br>    for _ in range(COUNT):<br>        x += 1<br>start = time.time()<br><br>thread1 = threading.Thread(target=cpu_heavy)<br>thread2 = threading.Thread(target=cpu_heavy)<br><br>thread1.start()<br>thread2.start()<br><br>thread1.join()<br>thread2.join()<br><br>print(f&quot;Threads (CPU-bound): {time.time() - start:.2f}s&quot;)</pre><p>What you’ll see: The two threads don’t make it faster. It may even take longer than running one after another.</p><p>Why? They’re both fighting for the GIL. Only one can do actual Python work at a time.</p><h3>Example #2: CPU-Bound Task (With Multiprocessing)</h3><p>Now let’s try the same workload using multiprocessing:</p><pre>from multiprocessing import Process<br>import time<br><br>COUNT = 50_000_000<br><br>def cpu_heavy():<br>    x = 0<br>    for _ in range(COUNT):<br>        x += 1<br><br>start = time.time()<br><br>p1 = Process(target=cpu_heavy)<br>p2 = Process(target=cpu_heavy)<br><br>p1.start()<br>p2.start()<br><br>p1.join()<br>p2.join()<br><br>print(f&quot;Processes (CPU-bound): {time.time() - start:.2f}s&quot;)</pre><p>Now it’s much faster! Each process gets its own GIL and memory space — so they can run in parallel across CPU cores.</p><h3>Example #3: I/O-Bound Task (With Threads)</h3><p>Let’s simulate a real backend workload — calling a slow API:</p><pre>import threading<br>import time<br>import requests<br><br>URL = &quot;&lt;https://httpbin.org/delay/2&gt;&quot;  # waits 2 seconds before replying<br><br>def fetch():<br>    response = requests.get(URL)<br>    print(response.status_code)<br><br>start = time.time()<br>threads = [threading.Thread(target=fetch) for _ in range(5)]<br><br>for t in threads:<br>    t.start()<br><br>for t in threads:<br>    t.join()<br><br>print(f&quot;Threads (I/O-bound): {time.time() - start:.2f}s&quot;)</pre><p>Even though each request takes 2 seconds, the whole program finishes in ~2 seconds, not 10.</p><p>Why? Because requests.get() blocks on I/O and releases the GIL, allowing other threads to run.</p><h3>Threads Work Well With I/O</h3><p>In backend APIs, you often:</p><ul><li>Call other APIs</li><li>Talk to databases</li><li>Read files</li></ul><p>These are all I/O-bound, so threading can actually help even with the GIL. For example, a simple FastAPI endpoint like:</p><pre>@app.get(&quot;/status&quot;)<br>def get_status():<br>    requests.get(&quot;&lt;https://a-service.com/ping&gt;&quot;)<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p>Can scale better under concurrent users if served by a thread-based ASGI server like Uvicorn with workers.</p><h3>asyncio vs multiprocessing vs threading</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9AtgI6OL1xIXD_4bpEuqQ.png" /></figure><h3>Summary</h3><ul><li>Python threads won’t help you speed up CPU-heavy code because of the GIL.</li><li>For CPU-bound work, use multiprocessing, or call out to C extensions that release the GIL.</li><li>For I/O-heavy work, Python threads (or asyncio) are great.</li><li>Benchmark your own code before optimizing. You might be blaming the wrong thing.</li></ul><p>The original post is <a href="https://hevalhazalkurt.com/blog/how-the-gil-affects-real-python-workloads/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=265408412798" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Singleton with Async/Await in Python]]></title>
            <link>https://hevalhazalkurt.medium.com/implementing-singleton-with-async-await-in-python-9a456e10d746?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a456e10d746</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 15:49:17 GMT</pubDate>
            <atom:updated>2025-09-22T15:49:17.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3n6RSTZiXIF5Ermt4F7Cgg.jpeg" /></figure><p>The Singleton pattern is one of the most well-known design patterns in software development. It ensures that a class has only one instance and provides a global point of access to it. In synchronous Python, this is fairly straightforward. But when you step into the world of asynchronous programming, things get a bit trickier.</p><p>In this blog post, we’ll start with the basics of the Singleton pattern, then move into the async/await world, and finally explore advanced usage patterns and real-life backend scenarios. We’ll also highlight common pitfalls and how to avoid them.</p><h3>The Basics: What is a Singleton?</h3><p>A Singleton is a class that can only have one instance throughout the lifetime of an application. In Python, this is usually implemented by overriding the __new__ method or using metaclasses.</p><h3>Classic Singleton (Synchronous)</h3><pre>class Singleton:<br>    _instance = None<br><br>    def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super().__new__(cls)<br>        return cls._instance</pre><p>This pattern works fine when everything is synchronous. But what happens if you need to initialize the singleton asynchronously, like when making a database connection?</p><h3>Enter Asynchronous Python</h3><p>Asynchronous Python allows you to write non-blocking code using async and await. It’s perfect for I/O-bound tasks like API calls, database queries, or file operations. But here’s the catch: you can’t await inside __new__ or __init__, because they&#39;re not async functions. So how do you create an async-aware Singleton?</p><h3>Async Singleton Pattern</h3><p>Let’s say we want to create a Singleton that manages a database connection. The connection setup is asynchronous. For example using an async PostgreSQL client.</p><h3>Example 1: Async Database Connector Singleton</h3><pre>import asyncio<br><br>class AsyncDBConnector:<br>    _instance = None<br>    _lock = asyncio.Lock()<br><br>    def __init__(self):<br>        self.connection = None<br><br>    @classmethod<br>    async def get_instance(cls):<br>        if cls._instance is None:<br>            async with cls._lock:<br>                if cls._instance is None:<br>                    instance = cls()<br>                    await instance._connect()<br>                    cls._instance = instance<br>        return cls._instance<br><br>    async def _connect(self):<br>        # Simulate async DB connection<br>        await asyncio.sleep(1)<br>        self.connection = &quot;Connected to DB&quot;</pre><h3>Why it works:</h3><ul><li>We use a class method get_instance to create the instance.</li><li>We wrap it with a lock to ensure thread safety in a multi-tasking environment.</li><li>The _connect method is async and performs the setup.</li></ul><h3>Usage:</h3><pre>async def main():<br>    db = await AsyncDBConnector.get_instance()<br>    print(db.connection)<br><br><br>asyncio.run(main())</pre><h3>Example 2: Singleton Config Loader</h3><p>Let’s build a singleton config loader that reads secrets from an external async API like AWS Secrets Manager.</p><pre>class ConfigManager:<br>    _instance = None<br>    _lock = asyncio.Lock()<br><br>    def __init__(self):<br>        self.config = {}<br>    <br>    @classmethod<br>    async def get_instance(cls):<br>        if cls._instance is None:<br>            async with cls._lock:<br>                if cls._instance is None:<br>                    instance = cls()<br>                    await instance._load_config()<br>                    cls._instance = instance<br>        return cls._instance<br>    <br>    async def _load_config(self):<br>        await asyncio.sleep(0.5)  # Simulate network request<br>        self.config = {<br>            &quot;DATABASE_URL&quot;: &quot;postgresql://user:pass@host/db&quot;,<br>            &quot;API_KEY&quot;: &quot;abc123xyz&quot;<br>        }<br><br># Usage<br>async def main():<br>    config = await ConfigManager.get_instance()<br>    print(config.config[&quot;API_KEY&quot;])<br><br>asyncio.run(main())</pre><h3>Using Async Singleton in FastAPI</h3><p>FastAPI is one of the most popular async web frameworks in Python. It thrives on non-blocking I/O and dependency injection. Let’s see how you can integrate an async Singleton pattern into a FastAPI app.</p><h3>Use Case: Shared Redis Client or DB Connection</h3><p>Imagine you have a Redis connection that should be initialized once and reused across all endpoints.</p><pre>from fastapi import FastAPI, Depends<br>import asyncio<br><br><br>class RedisClient:<br>    _instance = None<br>    _lock = asyncio.Lock()<br>    def __init__(self):<br>        self.connection = None<br><br>    @classmethod<br>    async def get_instance(cls):<br>        if cls._instance is None:<br>            async with cls._lock:<br>                if cls._instance is None:<br>                    instance = cls()<br>                    await instance._connect()<br>                    cls._instance = instance<br>        return cls._instance<br><br>    async def _connect(self):<br>        await asyncio.sleep(1)<br>        self.connection = &quot;Simulated Redis Connection&quot;<br><br># Dependency wrapper<br>async def get_redis_client() -&gt; RedisClient:<br>    return await RedisClient.get_instance()<br><br># FastAPI app<br>app = FastAPI()<br><br>@app.get(&quot;/status&quot;)<br>async def status(redis: RedisClient = Depends(get_redis_client)):<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;redis&quot;: redis.connection}</pre><ul><li>get_redis_client() is declared as an async dependency.</li><li>The Singleton instance is resolved on demand and shared afterward.</li><li>This is perfect for Redis, PostgreSQL, and custom HTTP clients like aiohttp or httpx.</li></ul><h3>Common Pitfalls</h3><h3>1. Trying to await in __init__</h3><p>This will fail:</p><pre>class BadExample:<br>    def __init__(self):<br>        await self.setup()  # SyntaxError</pre><p>You can’t await inside __init__. Use a separate async setup method.</p><h3>2. Not Using a Lock</h3><p>If multiple coroutines call get_instance() at the same time, you might end up with multiple instances. Always protect instantiation with an asyncio.Lock() to ensure thread safety.</p><h3>A Few Tips</h3><h4>Make Singleton Test-Friendly</h4><p>Sometimes it’s useful to reset or override the Singleton during testing.</p><pre>@classmethod<br>def reset_instance(cls):<br>    cls._instance = None</pre><h4>Avoid Global State</h4><p>Even with Singletons, be cautious not to abuse them as global variables. It’s best to inject them where needed like as constructor args.</p><h4>Lazy Initialization</h4><p>Delay the heavy work until it’s really needed. This keeps startup time low.</p><h3>Wrapping Up</h3><p>Singletons in async Python aren’t hard, but they do require you to rethink how and when your object is created. The key takeaway is: move all await logic out of __init__ and into an async method, and make sure to guard instance creation with an asyncio.Lock().</p><p>Used right, an async Singleton can be a great tool for managing shared resources like DB connections, config loaders, and API clients in modern backend applications.</p><p>The original post is <a href="https://hevalhazalkurt.com/blog/implementing-singleton-with-asyncawait-in-python/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a456e10d746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Async Context Managers in Python]]></title>
            <link>https://hevalhazalkurt.medium.com/understanding-async-context-managers-in-python-c055d862870f?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c055d862870f</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 15:50:15 GMT</pubDate>
            <atom:updated>2025-07-17T15:50:15.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nob0svorFybVQNABFsT4Ag.jpeg" /></figure><p>When working with asynchronous code in Python, you’re probably familiar with async def, await, and maybe even tools like aiohttp or asyncpg. But if you&#39;ve ever wondered how to manage resources cleanly and safely in async code, then it&#39;s time to meet a powerful tool: the async context manager.</p><p>In this post, we’ll take a deep dive into what async context managers are, why they matter, and how to use them effectively in real-world backend applications.</p><h3>What Is a Context Manager Again?</h3><p>Before we dive into the async version, let’s briefly recall what a context manager is in general. In Python, context managers are commonly used with the with statement to manage setup and teardown logic:</p><pre>with open(&#39;log.txt&#39;, &#39;w&#39;) as f:<br>    f.write(&quot;Logging something important.&quot;)</pre><p>The file is automatically closed once the block ends even if an error occurs. This pattern is clean and safe.</p><h3>Why Do We Need Async Context Managers?</h3><p>The traditional with block works fine for synchronous code. But what if your resource like a database connection, network socket, or HTTP session, needs to be handled asynchronously? That’s where async context managers come in. They’re used with async with, and they allow you to:</p><ul><li>Await asynchronous setup/teardown.</li><li>Manage resources like connections in async code.</li><li>Avoid race conditions and resource leaks.</li></ul><h3>How Async Context Managers Work</h3><p>You use async with to enter an asynchronous context:</p><pre>class AsyncLogger:<br>    async def __aenter__(self):<br>        print(&quot;Async Enter&quot;)<br>        return self<br><br>    async def __aexit__(self, exc_type, exc_val, tb):<br>        print(&quot;Async Exit&quot;)<br><br><br>async def main():<br>    async with AsyncLogger():<br>        print(&quot;Inside block&quot;)<br><br>asyncio.run(main())</pre><p><strong>So what’s happening here?</strong></p><ul><li>__aenter__: Think of it as an async version of __enter__. You can await things here.</li><li>__aexit__: Similar to __exit__, but awaitable.</li></ul><h3>Backend Example 1: Managing an Async HTTP Session with aiohttp</h3><p>Let’s say you’re fetching data from a REST API in an async backend service:</p><pre>import aiohttp<br>import asyncio<br><br>async def fetch_data():<br>    async with aiohttp.ClientSession() as session:<br>        async with session.get(&quot;&lt;https://api.example.com/data&gt;&quot;) as response:<br>            data = await response.json()<br>            print(data)<br><br># asyncio.run(fetch_data())</pre><p><strong>Why this is great:</strong></p><ul><li>The session and request are both async context managers.</li><li>They’re automatically closed and cleaned up.</li><li>No need to manually close connections.</li></ul><h3>Backend Example 2: Async Database Connection Pool</h3><p>Let’s say you’re building a FastAPI app that talks to PostgreSQL using asyncpg:</p><pre>import asyncpg<br>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    app.state.pool = await asyncpg.create_pool(database=&quot;testdb&quot;)<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown():<br>    await app.state.pool.close()<br><br>@app.get(&quot;/users&quot;)<br>async def get_users():<br>    async with app.state.pool.acquire() as conn:<br>        rows = await conn.fetch(&quot;SELECT * FROM users&quot;)<br>        return [dict(row) for row in rows]</pre><p><strong>Why use </strong><strong>async with for DB?</strong></p><ul><li>Automatically releases connections back to the pool.</li><li>Prevents DB connection leaks.</li><li>Keeps code clean and easy to maintain.</li></ul><h3>Building Your Own Async Context Manager with contextlib</h3><p>You can also build async context managers easily using contextlib.asynccontextmanager:</p><pre>from contextlib import asynccontextmanager<br><br>@asynccontextmanager<br>async def temporary_file():<br>    print(&quot;Setting up async resource&quot;)<br>    yield &quot;/tmp/temp.txt&quot;<br>    print(&quot;Cleaning up async resource&quot;)<br><br><br>async def main():<br>    async with temporary_file() as path:<br>        print(f&quot;Using temp file at {path}&quot;)<br><br># asyncio.run(main())</pre><p>This approach is simpler and cleaner than defining a full class with __aenter__/__aexit__ when all you need is a quick setup/teardown pattern.</p><h3>Advanced Patterns</h3><h3>Nesting Async Context Managers</h3><p>You can nest multiple async contexts just like sync ones:</p><pre>async with aiohttp.ClientSession() as session:<br>    async with session.get(url) as response:<br>        data = await response.text()</pre><p>Or combine them with async with and commas:</p><pre>async with manager1(), manager2():<br>    ...</pre><h3>Combining with async for</h3><pre>async with some_streaming_context() as stream:<br>    async for chunk in stream:<br>        await process(chunk)</pre><p>Useful when reading big files or streaming API responses.</p><h3>Using Inside Dependency Injection (FastAPI Example)</h3><pre>@asynccontextmanager<br>async def get_db():<br>    async with db_pool.acquire() as conn:<br>        yield conn<br><br><br>@app.get(&quot;/products&quot;)<br>async def read_products(db = Depends(get_db)):<br>    rows = await db.fetch(&quot;SELECT * FROM products&quot;)<br>    return rows</pre><h3>Common Pitfalls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyfkeUgm13lSMq-fdtoQAA.png" /></figure><h3>Cheat Sheet</h3><pre># Basic Structure<br>class MyAsyncManager:<br>    async def __aenter__(self): ...<br>    async def __aexit__(self, exc_type, exc, tb): ...<br><br><br># Shortcut with contextlib<br>@asynccontextmanager<br>async def my_manager():<br>    yield resource<br><br><br># Usage<br>async with my_manager() as res:<br>    await do_something(res)</pre><h3>Final Thoughts</h3><p>Async context managers are a must-know tool for writing clean, safe, and efficient asynchronous code in modern Python. Whether you’re dealing with HTTP clients, database pools, or temporary async resources, they help you stay in control without clutter.</p><p>If you’re writing backend services with FastAPI, aiohttp, or Quart, mastering async context managers will make your architecture more robust and professional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c055d862870f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Underscores EP13: Metaprogramming Methods (__class__, __bases__, __mro__…]]></title>
            <link>https://hevalhazalkurt.medium.com/behind-the-underscores-ep13-metaprogramming-methods-class-bases-mro-8c96c46eabbe?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c96c46eabbe</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 16:25:12 GMT</pubDate>
            <atom:updated>2025-07-11T16:25:12.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Behind the Underscores EP13: Metaprogramming Methods (__class__, __bases__, __mro__, __instancecheck__)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyOcj5TA1HaYegLLDDXlcg.png" /></figure><p>Metaprogramming in Python is like programming about programming. It means writing code that can change how other code behaves. Sounds deep? It is. But it’s also powerful. In this post, we’ll break down some of the most important metaprogramming methods in Python. These include __class__, __bases__, __mro__, __instancecheck__, and __subclasshook__. We’ll keep things practical and show how they might be useful in real backend development scenarios.</p><h3>First, What Is a Metaclass?</h3><p>A metaclass is simply the class of a class. Just like objects are created from classes, classes themselves are created from metaclasses.</p><p>Think of it this way:</p><ul><li>🧱 You use a class to build objects.</li><li>🛠️ Python uses a metaclass to build classes.</li></ul><p>By default, Python uses a built-in metaclass called type, but you can define your own to control how classes behave when they’re created.</p><p>Here’s a super simple example:</p><pre>class MyMeta(type):<br>    def __new__(cls, name, bases, dct):<br>        print(f\\&quot;Creating class: {name}\\&quot;)<br>        return super().__new__(cls, name, bases, dct)<br><br><br>class MyClass(metaclass=MyMeta):<br>    pass<br><br><br># Output: Creating class: MyClass</pre><p>As you can see, MyMeta intercepted the moment MyClass was being defined and injected its own logic. That’s the core idea.</p><h3>What’s Python’s Default Metaclass Structure?</h3><p>Like I mentioned before, in Python, the default metaclass is type. Every class you define is actually an instance of type, unless you say otherwise.</p><pre>class A:<br>    pass<br><br>print(type(A))  # &lt;class &#39;type&#39;&gt;</pre><p>Even built-in classes follow this structure:</p><pre>print(type(int))     # &lt;class &#39;type&#39;&gt;<br>print(type(object))  # &lt;class &#39;type&#39;&gt;</pre><p>So what does type actually do? It:</p><ul><li>Creates new classes when you define them</li><li>Handles the __mro__, __bases__, and other class-level mechanics</li><li>Serves as the parent of all metaclasses</li></ul><p>Unless you explicitly specify another metaclass, Python will always fall back to type. This is what makes metaprogramming possible in the first place. You’re building on top of Python’s default behavior and customizing it to your needs.</p><p>Now, let’s look at how we can make them custom for our codes.</p><h3>1. __class__: Who Are You Really?</h3><p>The __class__ attribute tells you the class of an instance. It’s a simple yet powerful way to inspect objects at runtime.</p><h3>Example: Debugging API Payloads</h3><p>Imagine you’re working on a Flask or FastAPI backend. You receive an object that should be a UserPayload, but you want to double-check.</p><pre>class UserPayload:<br>    pass<br><br>data = UserPayload()<br>print(data.__class__)  # &lt;class &#39;__main__.UserPayload&#39;&gt;</pre><h3>Real-life use</h3><p>Let’s say you log incoming data types for debugging:</p><pre>def log_type(obj):<br>    print(f&quot;Received object of type: {obj.__class__.__name__}&quot;)</pre><h3>2. __bases__: Know Your Parents</h3><p>This attribute gives you the immediate parent classes of a class. It’s like checking a family tree.</p><h3>Example: Plugin System</h3><p>Say you’re building a plugin system and you want to validate that a plugin inherits from BasePlugin:</p><pre>class BasePlugin:<br>    pass<br><br>class MyPlugin(BasePlugin):<br>    pass<br><br>print(MyPlugin.__bases__)  # (&lt;class &#39;__main__.BasePlugin&#39;&gt;,)</pre><h3>Real-life use</h3><p>When auto-discovering classes for registration:</p><pre>if BasePlugin in MyPlugin.__bases__:<br>    register_plugin(MyPlugin)</pre><h3>3. __mro__: Method Resolution Order</h3><p>This is how Python decides which method to call when there are multiple inheritance paths. You can inspect it to understand how your code will behave.</p><h3>Example: Service Layer Conflict Resolution</h3><p>In a layered service architecture, if two parent classes implement the same method, __mro__ helps resolve ambiguity.</p><pre>class AuthService:<br>    def execute(self):<br>        print(&quot;Auth logic&quot;)<br><br><br>class LoggingService:<br>    def execute(self):<br>        print(&quot;Logging logic&quot;)<br><br><br>class UserService(AuthService, LoggingService):<br>    pass<br><br><br>print([cls.__name__ for cls in UserService.__mro__])<br># [&#39;UserService&#39;, &#39;AuthService&#39;, &#39;LoggingService&#39;, &#39;object&#39;]</pre><p>Python will call AuthService.execute() first.</p><h3>4. __instancecheck__: Redefining isinstance()</h3><p>You can override how isinstance() works by using a metaclass and implementing __instancecheck__.</p><h3>Example: Duck Typing Microservices</h3><p>In microservices, you often care about behavior, not type. Suppose anything with a .run() method is a valid Job:</p><pre>class JobMeta(type):<br>    def __instancecheck__(cls, instance):<br>        return callable(getattr(instance, &#39;run&#39;, None))<br><br><br>class Job(metaclass=JobMeta):<br>    pass<br><br><br>class EmailJob:<br>    def run(self):<br>        print(&quot;Sending email&quot;)<br><br><br>print(isinstance(EmailJob(), Job))  # True</pre><p>Even though EmailJob doesn’t inherit from Job, it’s considered an instance.</p><h3>5. __subclasshook__: Virtual Subclasses</h3><p>This is used when you want issubclass() to return True even when there is no inheritance as long as the class behaves like it should.</p><h3>Example: Abstract Base Classes in a Backend</h3><p>Let’s define a repository interface that all storage backends should implement:</p><pre>from abc import ABCMeta<br><br>class Repository(metaclass=ABCMeta):<br>    @classmethod<br>    def __subclasshook__(cls, subclass):<br>        return (hasattr(subclass, &#39;save&#39;) and<br>                hasattr(subclass, &#39;delete&#39;))<br><br><br>class SQLRepository:<br>    def save(self): pass<br>    def delete(self): pass<br><br><br>print(issubclass(SQLRepository, Repository))  # True</pre><p>This is great when you want to enforce contracts by behavior rather than strict inheritance.</p><h3>When Do We Actually Need Metaprogramming?</h3><p>Most of the time, plain classes and functions will get you pretty far in Python. But metaprogramming becomes useful when your code needs to be more dynamic, self-aware, or extendable.</p><p>Here are some situations where metaprogramming methods shine:</p><ul><li><strong>Framework Design:</strong> If you’re building your own framework like Django or FastAPI, you’ll often need to hook into how classes are created or validated.</li><li><strong>Plugin Systems:</strong> Want to load plugins automatically just by defining new classes? __subclasshook__ and __bases__ can help.</li><li><strong>Custom Validation Rules:</strong> You might want to check if objects follow certain rules without enforcing inheritance which is great for loose coupling.</li><li><strong>Duck Typing by Behavior:</strong> Instead of checking inheritance, you check if an object behaves a certain way like having a .run() method.</li><li><strong>Debugging or Logging:</strong> Use __class__, __mro__, and others to inspect what kind of object you&#39;re dealing with at runtime.</li></ul><p>In short, when you want to make Python smarter about how it sees and uses classes or object, this is when metaprogramming helps.</p><h3>When Should We Be Careful Using Them?</h3><p>Just because you can use metaprogramming doesn’t mean you always should. These tools are powerful, but they come with sharp edges.</p><p>Here’s when you should take a step back:</p><ul><li><strong>Readability Drops:</strong> Overusing metaclasses and custom hooks can make code really hard to follow for other developers and even future you.</li><li><strong>Debugging Becomes Harder:</strong> If isinstance() or issubclass() doesn’t behave normally, that can cause confusion and bugs that are tough to trace.</li><li><strong>Performance Overhead:</strong> Dynamically checking attributes in __instancecheck__ or __subclasshook__ might slow things down if used on large datasets or high-traffic systems.</li><li><strong>Third-Party Conflicts:</strong> Some libraries or tools may expect default behaviors, so customizing too much might break integrations.</li></ul><p>Use them like spices: a pinch here and there can make your code elegant. Overdo it, and you’ll ruin the dish.</p><h3>Final Thoughts</h3><p>Metaprogramming methods like __class__, __bases__, __mro__, __instancecheck__, and __subclasshook__ are not just abstract ideas. They give you fine-grained control over how your code behaves, especially in large-scale backend systems where flexibility, extensibility, and loose coupling are essential.</p><p>Use them wisely, and you’ll unlock the ability to write smarter, more adaptive Python code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c96c46eabbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Underscores EP12: Descriptor Protocol (__get__, __set__, __delete__)]]></title>
            <link>https://hevalhazalkurt.medium.com/behind-the-underscores-ep12-descriptor-protocol-get-set-delete-731d81307379?source=rss-8d37d1c078f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/731d81307379</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Heval Hazal Kurt]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 14:33:14 GMT</pubDate>
            <atom:updated>2025-07-10T14:33:14.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPbby4E20AHgGQh9pOmwLQ.jpeg" /></figure><p>Python is full of powerful features that let you write clean, reusable, and elegant code. One of these features, often misunderstood or underused, is the descriptor protocol. Descriptors let you hook into attribute access and build flexible, reusable behaviors around it. They’re used heavily behind the scenes in properties, class methods, static methods, and even Django ORM models.</p><p>In this blog post, we’ll break down the descriptor protocol special methods: __get__, __set__, and __delete__, and see how they’re useful in backend development.</p><h3>What Is a Descriptor?</h3><p>A descriptor is simply a class that implements any of the following methods:</p><ul><li>__get__(self, instance, owner)</li><li>__set__(self, instance, value)</li><li>__delete__(self, instance)</li></ul><p>Once a descriptor class is assigned as a class attribute, it controls access to that attribute. This allows you to customize what happens when someone gets, sets, or deletes an attribute from an instance of the owner class.</p><h3>The Three Special Methods</h3><h3>1. __get__: Controls how an attribute is read</h3><pre>def __get__(self, instance, owner):<br>    # Return the value to be used when the attribute is accessed</pre><ul><li>instance: the instance accessing the attribute</li><li>owner: the class of the instance</li></ul><h3>2. __set__: Controls how an attribute is written</h3><pre>def __set__(self, instance, value):<br>    # Handle setting a new value to the attribute</pre><ul><li>value: the value being assigned to the attribute</li></ul><h3>3. __delete__: Controls what happens when an attribute is deleted</h3><pre>def __delete__(self, instance):<br>    # Handle deletion of the attribute</pre><p>Now, let’s explore them in a few real-life backend examples.</p><h3>Example 1: Using a Descriptor in a Product Tag System</h3><p>Imagine you’re building a backend for an e-commerce site. Each product can have tags, and these tags store various metadata like value, shape, and name. Internally, this data lives in a data object, but you want to make access clean and consistent on the main Tag class.</p><pre>class TagDataDescriptor:<br>    def __init__(self, attr):<br>        self.attr = attr<br><br>    def __get__(self, tag, owner):<br>        return getattr(tag.data, self.attr)<br><br>    def __set__(self, tag, value):<br>        setattr(tag.data, self.attr, value)<br><br><br>class Tag:<br>    value = TagDataDescriptor(&#39;value&#39;)<br>    shape = TagDataDescriptor(&#39;shape&#39;)<br>    name = TagDataDescriptor(&#39;name&#39;)<br>    def __init__(self, data):<br>        self.data = data<br><br><br>class TagData:<br>    def __init__(self, value, shape, name):<br>        self.value = value<br>        self.shape = shape<br>        self.name = name<br><br><br># Usage<br>raw_data = TagData(&quot;sale&quot;, &quot;circle&quot;, &quot;Discount&quot;)<br>tag = Tag(raw_data)<br>print(tag.value)   # Prints: sale<br><br>tag.shape = &quot;square&quot;<br>print(tag.data.shape)  # Prints: square</pre><h3>So, What’s Happening</h3><ul><li>When you do tag.value, the descriptor’s __get__ method is triggered.</li><li>It fetches the actual data from tag.data.value.</li><li>When you set tag.shape = &quot;square&quot;, the descriptor forwards it to tag.data.shape = &quot;square&quot;.</li></ul><h3>Why It’s Useful in Backend Code</h3><ul><li>You keep your API clean and simple.</li><li>You decouple the internal data structure from the public interface.</li><li>You can change how the data is stored later without touching external code.</li></ul><h3>Example 2: Validating Configuration</h3><p>In this second example, let’s say you’re managing application settings like port numbers or environment variables. You want to validate values when they’re set, but keep your class definitions neat.</p><pre>class PortValidator:<br>    def __get__(self, instance, owner):<br>        return instance.__dict__.get(&#39;_port&#39;)<br><br>    def __set__(self, instance, value):<br>        if not (1024 &lt;= value &lt;= 65535):<br>            raise ValueError(&quot;Port must be between 1024 and 65535&quot;)<br>        instance.__dict__[&#39;_port&#39;] = value<br><br>    def __delete__(self, instance):<br>        raise AttributeError(&quot;Port can&#39;t be deleted&quot;)<br><br><br>class AppConfig:<br>    port = PortValidator()<br>    def __init__(self, port):<br>        self.port = port<br><br><br># Usage<br>config = AppConfig(8080)<br>print(config.port)  # 8080<br>config.port = 70000  # Raises ValueError</pre><h3>So, What’s Happening Again</h3><ul><li>__set__ checks that the port is within a valid range.</li><li>__get__ fetches the value from instance’s __dict__.</li><li>__delete__ blocks deletion to avoid broken config states.</li></ul><h3>And Why It’s Useful in Backend Code</h3><ul><li>You enforce data validation at the attribute level.</li><li>You avoid repeating validation logic in multiple places.</li><li>You define consistent rules for critical settings.</li></ul><h3>Final Thoughts</h3><p>The descriptor protocol is a hidden gem in Python that can supercharge your backend design patterns. By hooking into __get__, __set__, and __delete__, you can build smart attributes that:</p><ul><li>Forward access to other layers like data models</li><li>Automatically validate and control data</li><li>Clean up repetitive property definitions</li></ul><p>Understanding descriptors might take a little practice, but once you get used to them, they become a very natural and Pythonic way to organize your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731d81307379" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>