Skip to main content

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

Metadata

Release files for lazy-decorators 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lazy-decorators 1.0.3
File Size Uploaded Provenance Actions
lazy_decorators-1.0.3.tar.gz 3.9 kB Without provenance Details for lazy_decorators-1.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lazy-decorators 1.0.3
File Interpreter ABI Platform Actions
lazy_decorators-1.0.3-py3-none-any.whl Python 3 none any Details for lazy_decorators-1.0.3-py3-none-any.whl

Total release size: 9.0 kB

Release files / lazy_decorators-1.0.3.tar.gz

Download URL lazy_decorators-1.0.3.tar.gz
Size 3.9 kB
Tags Source
SHA-256 checksum
How to use checksums
8eac714374fa9a4ffcfc873e425053a2065891f7b6df2db3db099f685655c447
BLAKE2b-256 checksum
How to use checksums
8971206bf7f7e475fe276d84d06878666ee90fbeeb1307b574b89b3a4274c6ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / lazy_decorators-1.0.3-py3-none-any.whl

Download URL lazy_decorators-1.0.3-py3-none-any.whl
Size 5.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0edace0b6bc3584b9233a47d87038ecb567289269236e5016aa2888fd528dcfb
BLAKE2b-256 checksum
How to use checksums
fd1f13846322bc264eeb69fe6d80941b1da385d871f555688204add75e5e8279
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for lazy-decorators 1.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page