Skip to main content

Decorators to define lazy methods and functions

Project description

lazy-decorators

The lazy-decorators package provides a set of decorators for implementing lazy and cached properties in Python. It allows expensive computations to be deferred until they are actually needed and caches the results for later use.


Installation

pip install lazy-decorators

Concept

In applications where operations like database connections or heavy data processing exist, executing them early can waste resources. With lazy-decorators, such properties are evaluated only when accessed, and the results are cached. If dependencies change, the cache can be invalidated manually or automatically.

The package provides two main types of decorators:

  • NotThreadSafe: For single-threaded environments
  • ThreadSafe: For multi-threaded environments

Example Usage (NotThreadSafe)

from lazy_decorators import NotThreadSafe


class DatabaseClient(NotThreadSafe.CachedPropertyDependencyMixin):
    
    def __init__(self, configuration):
        self.configuration = configuration
    
    # The connection is created lazily and cached until dependencies change
    @NotThreadSafe.dependent_cached_property(depends_on=['configuration'])
    def connection(self):
        # Create a connection object based on current configuration
        return f'Connection established with: {self.configuration}'


# Create a client with initial configuration
client = DatabaseClient(configuration={'user': 'user_1', 'password': 'pass_1'})

# First access triggers connection creation and caches the result
connection_first = client.connection

# Subsequent access returns the cached connection
connection_cached = client.connection

# Changing configuration does not automatically recreate connection
client.configuration = {'user': 'user_2', 'password': 'pass_2'}
connection_stale = client.connection

# Manually invalidate the cache
client.invalidate_cache('connection')

# Next access recreates the connection and caches it
connection_new = client.connection

Example Usage (ThreadSafe)

from lazy_decorators import ThreadSafe
import time
import threading


class DataLoader(ThreadSafe.CachedPropertyDependencyMixin):
    
    def __init__(self, file_path):
        self.file_path = file_path
    
    # Data is loaded lazily and shared safely across multiple threads
    @ThreadSafe.dependent_cached_property(depends_on=['file_path'])
    def data(self):
        # Simulate loading heavy data from file
        time.sleep(2)
        return f'Data loaded successfully from {self.file_path}'


loader = DataLoader(file_path='dataset.csv')


# Function to access data concurrently
def load_data_task():
    # Only first thread triggers data loading, others use cached value
    data = loader.data


# Launch multiple threads accessing the property
threads = [threading.Thread(target=load_data_task) for _ in range(3)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

# Change dependency and invalidate cache
loader.file_path = 'dataset_v2.csv'
loader.invalidate_cache('data')

# Next access reloads the data and caches it again
data_new = loader.data

Suggested Study Path

  1. Caches
  2. Usage examples: how_to_use.py
  3. Lazy object instantiation: lazy_instantiation.py
  4. Thread-Safe versions:

Use Cases

  • Managing heavy resources such as databases or large files
  • Expensive computations that are called repeatedly
  • Dynamic dependencies between properties
  • Multi-threaded projects requiring safe caching

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lazy_decorators-1.0.2.tar.gz (3.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lazy_decorators-1.0.2-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file lazy_decorators-1.0.2.tar.gz.

File metadata

  • Download URL: lazy_decorators-1.0.2.tar.gz
  • Upload date:
  • Size: 3.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for lazy_decorators-1.0.2.tar.gz
Algorithm Hash digest
SHA256 d008dd80d1eeb40d53d7671aa55495be1a1f4b92616dc7d950eefb7b5ef7a6ab
MD5 d9f1d019bb0f2c74a053df8200dfcc21
BLAKE2b-256 8e308f6c462152612bd3d6a324fce222ae841e573c0b9040cba115268d45a05d

See more details on using hashes here.

File details

Details for the file lazy_decorators-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for lazy_decorators-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a112014b8290d895f0ba025cc72bed95cfb290f1f5e6c3ccb5b0271f3a7d0739
MD5 02ab2c21ab2be74421c0df7dc8fbdf40
BLAKE2b-256 47605da863f87f38769d3e634a680a682f8b3cfa0961300cb1841f77529932cc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page