Python functools.cached_property Function

The functools.cached_property function in Python's functools module provides a decorator for caching the result of an instance method as a property. This can help improve performance by avoiding repeated calculations for properties that are expensive to compute.

Table of Contents

  1. Introduction
  2. functools.cached_property Function Syntax
  3. Examples
    • Basic Usage
    • Using with Expensive Calculations
    • Using with Data Fetching
  4. Real-World Use Case
  5. Conclusion

Introduction

The functools.cached_property function is used to cache the result of a method call as a property of an instance. This means that the method is only called once per instance, and subsequent accesses to the property return the cached result. This is useful for properties that are expensive to compute and do not change over the lifetime of the instance.

functools.cached_property Function Syntax

Here is how you use the functools.cached_property function:

from functools import cached_property

class MyClass:
    @cached_property
    def my_property(self):
        # Property computation
        pass

Parameters:

  • func: The method to be cached as a property.

Returns:

  • A property object that caches the result of the method.

Examples

Basic Usage

Cache the result of a simple property calculation.

Example

from functools import cached_property

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @cached_property
    def area(self):
        print("Calculating area...")
        return 3.14159 * self.radius ** 2

circle = Circle(10)
print(circle.area)  # Output: Calculating area...
                    #         314.159
print(circle.area)  # Output: 314.159 (cached result)

Using with Expensive Calculations

Cache the result of an expensive calculation.

Example

from functools import cached_property

class DataProcessor:
    def __init__(self, data):
        self.data = data

    @cached_property
    def processed_data(self):
        print("Processing data...")
        # Simulate an expensive computation
        return [d * 2 for d in self.data]

processor = DataProcessor([1, 2, 3])
print(processor.processed_data)  # Output: Processing data...
                                 #         [2, 4, 6]
print(processor.processed_data)  # Output: [2, 4, 6] (cached result)

Using with Data Fetching

Cache the result of a data fetching operation.

Example

from functools import cached_property
import requests

class WebPage:
    def __init__(self, url):
        self.url = url

    @cached_property
    def content(self):
        print(f"Fetching {self.url}...")
        response = requests.get(self.url)
        return response.text

page = WebPage('https://example.com')
print(page.content)  # Output: Fetching https://example.com...
                     #         (page content)
print(page.content)  # Output: (cached result)

Real-World Use Case

Lazy Loading

Use cached_property to implement lazy loading for expensive-to-compute properties.

Example

from functools import cached_property

class DatabaseConnection:
    def __init__(self, connection_string):
        self.connection_string = connection_string

    @cached_property
    def connection(self):
        print("Establishing database connection...")
        # Simulate establishing a database connection
        return f"Connection to {self.connection_string}"

db = DatabaseConnection('my_database')
print(db.connection)  # Output: Establishing database connection...
                      #         Connection to my_database
print(db.connection)  # Output: Connection to my_database (cached result)

Conclusion

The functools.cached_property function is used for caching the result of an instance method as a property. It helps improve performance by avoiding repeated calculations for properties that are expensive to compute and do not change over the lifetime of the instance. Proper usage can significantly enhance the efficiency and readability of your code.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare