DEV Community

Bar Dror
Bar Dror

Posted on Originally published at codebeneath.com

Python Descriptor Protocol and Property Caching: Lazy Evaluation Pattern

Originally published on Code Beneath.

Python's descriptor protocol is a low-level mechanism that powers properties, methods, and class variables. Understanding it lets you build reusable lazy-loading wrappers that cache expensive computations and defer work until a value is actually needed. A python descriptor protocol example with lazy evaluation caching will teach you what happens beneath the decorator syntax and show you when descriptors beat the simpler @property decorator for real production use.

What the Descriptor Protocol Actually Is

When you write obj.attribute, Python doesn't just return the value. It follows a lookup chain: check the instance dictionary first, then the class dictionary, then parent classes. If what it finds in the class dictionary has a __get__ method, Python calls that method instead of returning the raw value. That method is called a descriptor.

A descriptor is any object in a class that defines at least one of these three methods: __get__(self, instance, owner), __set__(self, instance, value), or __delete__(self, instance). When __get__ exists, it's a data descriptor if it also has __set__ or __delete__; otherwise it's a non-data descriptor. This distinction matters for attribute lookup order, which we will cover later.

Most Python developers never write descriptors. They use @property, @classmethod, @staticmethod. But those decorators are themselves descriptors. When you understand the protocol, you can build reusable caching wrappers that work across many classes without repeating boilerplate.

Building a Lazy-Loaded Descriptor with Caching

Here is a complete, runnable descriptor that computes a value once and caches the result:

class LazyProperty:
    """A descriptor that computes a value once and caches it on the instance."""

    def __init__(self, func):
        self.func = func
        self.name = func.__name__

    def __get__(self, instance, owner):
        if instance is None:
            return self

        # Check if the value is already cached on the instance.
        value = instance.__dict__.get(self.name)
        if value is None:
            # Compute and cache it.
            value = self.func(instance)
            instance.__dict__[self.name] = value

        return value


class DatabaseConnection:
    """Example: a connection that is expensive to set up."""

    def __init__(self, host):
        self.host = host

    @LazyProperty
    def connection(self):
        print(f"Opening connection to {self.host}...")
        # Simulate expensive operation.
        import time
        time.sleep(0.1)
        return f"connected to {self.host}"


if __name__ == "__main__":
    db = DatabaseConnection("localhost:5432")

    print("First access:")
    print(db.connection)

    print("\nSecond access (cached):")
    print(db.connection)

    print("\nInstance dict after caching:")
    print(db.__dict__)
Enter fullscreen mode Exit fullscreen mode

Run this code and you will see the message "Opening connection..." printed only once. The second access pulls the value straight from the instance dictionary, bypassing the descriptor. This is lazy evaluation: work is deferred until the attribute is first accessed.

Comparison: Descriptor vs. @property Decorator

Both descriptors and @property can wrap attribute access. The difference is reusability and control. A descriptor is a class you write once and use on many classes. @property is a decorator you apply to individual methods. Here is the same example written with @property:

class DatabaseConnectionProperty:
    """Same example using @property instead of a descriptor."""

    def __init__(self, host):
        self.host = host
        self._connection = None

    @property
    def connection(self):
        if self._connection is None:
            print(f"Opening connection to {self.host}...")
            import time
            time.sleep(0.1)
            self._connection = f"connected to {self.host}"

        return self._connection


if __name__ == "__main__":
    db = DatabaseConnectionProperty("localhost:5432")

    print("First access:")
    print(db.connection)

    print("\nSecond access (cached):")
    print(db.connection)
Enter fullscreen mode Exit fullscreen mode

This works fine for a single property. But if you need lazy caching on ten properties across five classes, you must write this cache logic ten times. With the descriptor, you write it once and decorate each property.

Aspect @property Decorator Descriptor Class
Reusability Must repeat cache logic per property Write once, use everywhere
Complexity Simple, familiar syntax Requires understanding __get__, __set__, __delete__
Control Limited to the method body Full control over lookup and binding
Inheritance Works with @classmethod, @staticmethod Must handle owner parameter carefully
Cache location Must use a private attribute like _value Can use instance.__dict__ directly (more efficient)

The Critical Gotcha: Descriptor Binding and Instance vs. Class Access

There is a subtle but important behavior: when you access a descriptor through the class (not an instance), the instance parameter in __get__ is None. Many developers miss this. Here is the gotcha in action:

class BuggyDescriptor:
    """A descriptor that does NOT handle class access correctly."""

    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        # BUG: We do not check if instance is None.
        value = instance.__dict__.get(self.func.__name__)
        if value is None:
            value = self.func(instance)
            instance.__dict__[self.func.__name__] = value
        return value


class Example:
    @BuggyDescriptor
    def expensive(self):
        return "computed"


# This works fine:
obj = Example()
print(obj.expensive)

# This crashes with AttributeError:
try:
    print(Example.expensive)
except AttributeError as e:
    print(f"ERROR: {e}")
Enter fullscreen mode Exit fullscreen mode

The fix, as shown in the LazyProperty class above, is to check if instance is None: return self. When accessing through the class, return the descriptor itself, not the computed value. This allows introspection and documentation tools to work correctly.

Descriptor with TTL: Time-Based Cache Expiration

In real production systems, you often need a cache that expires. Here is a descriptor that recomputes the value if the cache is older than a specified number of seconds:

import time


class CachedProperty:
    """A descriptor that caches a value with an optional TTL (time-to-live)."""

    def __init__(self, func, ttl=None):
        """
        Args:
            func: The function to call to compute the value.
            ttl: Time-to-live in seconds. None means cache forever.
        """
        self.func = func
        self.ttl = ttl
        self.name = func.__name__
        self.cache_key = f"_cached_{self.name}"
        self.time_key = f"_time_{self.name}"

    def __get__(self, instance, owner):
        if instance is None:
            return self

        now = time.time()

        # Check if cached value exists and is still fresh.
        cached_value = instance.__dict__.get(self.cache_key)
        cached_time = instance.__dict__.get(self.time_key)

        if cached_value is not None:
            if self.ttl is None:
                # No expiration.
                return cached_value
            elif cached_time is not None and (now - cached_time) < self.ttl:
                # Cache is still fresh.
                return cached_value

        # Compute new value and update cache.
        value = self.func(instance)
        instance.__dict__[self.cache_key] = value
        instance.__dict__[self.time_key] = now

        return value


class APIClient:
    """Example: a client that fetches user data from an API."""

    def __init__(self, user_id):
        self.user_id = user_id

    @CachedProperty(lambda self: self._fetch_user(), ttl=5)
    def user(self):
        pass

    def _fetch_user(self):
        print(f"Fetching user {self.user_id} from API...")
        import time
        time.sleep(0.05)
        return {"id": self.user_id, "name": "Alice"}


if __name__ == "__main__":
    client = APIClient(42)

    print("First fetch:")
    print(client.user)

    print("\nImmediate second fetch (cached):")
    print(client.user)

    print("\nWait 6 seconds, then fetch again:")
    time.sleep(6)
    print(client.user)
Enter fullscreen mode Exit fullscreen mode

This is more realistic. The cache expires after 5 seconds, forcing a fresh computation. Notice that we use separate keys for the value and the timestamp so they do not collide.

Use Case: ORM-Like Lazy Loading of Related Objects

Descriptors shine in ORM code (like SQLAlchemy or Django ORM) where you want to load related records only when accessed. Here is a simplified example:

class ForeignKey:
    """A descriptor that lazy-loads a related object from a database."""

    def __init__(self, related_class, foreign_key_field):
        self.related_class = related_class
        self.foreign_key_field = foreign_key_field
        self.name = None

    def __set_name__(self, owner, name):
        """Called when the descriptor is assigned to a class attribute."""
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self

        # Use the foreign key value to look up the related object.
        fk_value = getattr(instance, self.foreign_key_field)

        # Check cache on the instance.
        cache_key = f"_fk_{self.name}"
        related = instance.__dict__.get(cache_key)

        if related is None:
            # Simulate database query.
            print(f"SELECT * FROM {self.related_class.__name__} WHERE id = {fk_value}")
            related = self.related_class(id=fk_value)
            instance.__dict__[cache_key] = related

        return related


class Author:
    """A simple author entity."""

    def __init__(self, id, name="Unknown"):
        self.id = id
        self.name = name

    def __repr__(self):
        return f"Author(id={self.id}, name='{self.name}')"


class Book:
    """A book that has a foreign key to Author."""

    # This descriptor lazy-loads the author when accessed.
    author = ForeignKey(Author, "author_id")

    def __init__(self, title, author_id):
        self.title = title
        self.author_id = author_id


if __name__ == "__main__":
    book = Book("The Go Programming Language", author_id=1)

    print("Book created, author not loaded yet.")
    print(f"Book: {book.title}")

    print("\nAccessing book.author (triggers load):")
    print(book.author)

    print("\nAccessing book.author again (cached):")
    print(book.author)
Enter fullscreen mode Exit fullscreen mode

The __set_name__ method is a Python 3.6+ feature that lets the descriptor know its own attribute name without manual registration. The descriptor uses that to cache the related object in a predictable location on the instance.

Common Mistakes

Not checking for None in __get__: Always return self when instance is None. Otherwise, accessing the descriptor on the class will crash or behave unexpectedly.

Storing cache in a class-level dictionary: If you cache using a class-level dict keyed by id(instance), you will leak memory when instances are deleted. Always store cache in instance.__dict__.

Forgetting that data descriptors shadow instance dict: If your descriptor has both __get__ and __set__, it takes precedence over the instance dictionary. Non-data descriptors (only __get__) lose to instance dict. Plan your caching strategy accordingly.

Using __set_name__ without a fallback: __set_name__ is called at class definition time in Python 3.6+. In older code or when descriptors are created dynamically, you must pass the name explicitly or store it differently.

Testing Lazy Evaluation and Cache Behavior

Here is a simple test suite to verify descriptor caching works correctly:

import unittest
import time


class LazyProperty:
    def __init__(self, func):
        self.func = func
        self.name = func.__name__

    def __get__(self, instance, owner):
        if instance is None:
            return self

        value = instance.__dict__.get(self.name)
        if value is None:
            value = self.func(instance)
            instance.__dict__[self.name] = value

        return value


class Counter:
    def __init__(self):
        self.call_count = 0

    @LazyProperty
    def expensive(self):
        self.call_count += 1
        return self.call_count


class TestLazyProperty(unittest.TestCase):

    def test_computes_once(self):
        """The descriptor should compute the value only once."""
        obj = Counter()
        self.assertEqual(obj.expensive, 1)
        self.assertEqual(obj.expensive, 1)  # Still 1, not 2.
        self.assertEqual(obj.call_count, 1)

    def test_different_instances_separate_caches(self):
        """Each instance should have its own cached value."""
        obj1 = Counter()
        obj2 = Counter()

        self.assertEqual(obj1.expensive, 1)
        self.assertEqual(obj2.expensive, 1)
        self.assertEqual(obj1.expensive, 1)  # obj1 is still 1.

    def test_class_access_returns_descriptor(self):
        """Accessing on the class should return the descriptor itself."""
        self.assertIsInstance(Counter.expensive, LazyProperty)

    def test_cache_in_instance_dict(self):
        """The computed value should be stored in instance.__dict__."""
        obj = Counter()
        obj.expensive  # Trigger computation.
        self.assertIn("expensive", obj.__dict__)


if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

Save this as test_descriptor.py and run python -m unittest test_descriptor. All four tests should pass, confirming that lazy evaluation and caching work as expected.

Descriptor Protocol vs. __getattr__ and __getattribute__

Python also has __getattr__ and __getattribute__ for customizing attribute access. How do they compare? The descriptor protocol is cleaner for reusable property wrappers. __getattr__ is called only when normal lookup fails, so it is better for handling missing attributes. __getattribute__ is called for every attribute access, is very powerful, and very easy to mess up. For lazy caching of specific properties, descriptors are the right tool.

FAQ

Can I use descriptors with inheritance?

Yes. A descriptor defined on a parent class is found by the descriptor lookup protocol in child classes too. If you override it in a child class, the child class descriptor takes precedence. The owner parameter in __get__ tells you which class was used to access the descriptor, which is useful for introspection.

What is the performance cost of a descriptor vs. a plain attribute?

Accessing a descriptor is slightly slower than reading an instance variable because Python must call __get__. But once the value is cached in instance.__dict__, the second access is just a dict lookup, not much slower than a plain attribute. The performance hit is negligible for most applications. If you are caching expensive operations (database calls, network requests), the descriptor overhead is irrelevant.

Can a descriptor return a different value each time?

Yes, absolutely. Our CachedProperty example already does this: it returns a fresh value after the TTL expires. If you do not want caching at all, just compute and return the value in __get__ every time. The descriptor protocol does not require caching.

How do descriptors interact with @staticmethod and @classmethod?

Both @staticmethod and @classmethod are themselves descriptors. @staticmethod.__get__ returns the wrapped function unchanged. @classmethod.__get__ returns a bound method with the class as the first argument. You can nest them with custom descriptors, but it gets complex. For most use cases, pick one pattern and stick with it.

Can I delete a descriptor-cached value to force recomputation?

Yes. Implement __delete__(self, instance) and remove the cached value from instance.__dict__. Then the next access will recompute. You could also expose a method like invalidate() that clears the cache. This is especially useful for testing.

Top comments (0)