py-cachify 3.1.0__tar.gz → 3.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. py_cachify-3.2.0/PKG-INFO +427 -0
  2. py_cachify-3.2.0/README.md +392 -0
  3. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_cached.py +9 -9
  4. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_clients.py +6 -6
  5. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_helpers.py +10 -10
  6. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_lib.py +22 -22
  7. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_lock.py +10 -16
  8. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_pool.py +21 -21
  9. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_types/_common.py +9 -11
  10. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_types/_lock_wrap.py +3 -10
  11. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_types/_pool_wrap.py +3 -10
  12. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_types/_reset_wrap.py +4 -10
  13. {py_cachify-3.1.0 → py_cachify-3.2.0}/pyproject.toml +24 -7
  14. py_cachify-3.1.0/PKG-INFO +0 -272
  15. py_cachify-3.1.0/README.md +0 -240
  16. {py_cachify-3.1.0 → py_cachify-3.2.0}/.gitignore +0 -0
  17. {py_cachify-3.1.0 → py_cachify-3.2.0}/LICENSE +0 -0
  18. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/__init__.py +0 -0
  19. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/__init__.py +0 -0
  20. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_constants.py +0 -0
  21. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_exceptions.py +0 -0
  22. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_logger.py +0 -0
  23. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_pool_state.py +0 -0
  24. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/_backend/_types/__init__.py +0 -0
  25. {py_cachify-3.1.0 → py_cachify-3.2.0}/py_cachify/py.typed +0 -0
@@ -0,0 +1,427 @@
1
+ Metadata-Version: 2.5
2
+ Name: py-cachify
3
+ Version: 3.2.0
4
+ Summary: Caching, distributed locks, run-once guards and resource pools for sync and async Python, in memory or on Redis and DragonflyDB
5
+ Project-URL: Homepage, https://py-cachify.readthedocs.io/latest/
6
+ Project-URL: Documentation, https://py-cachify.readthedocs.io/latest/
7
+ Project-URL: Repository, https://github.com/EzyGang/py-cachify
8
+ Project-URL: Issues, https://github.com/EzyGang/py-cachify/issues
9
+ Project-URL: Changelog, https://py-cachify.readthedocs.io/latest/release-notes/
10
+ Author-email: Galtozzy <galtozzy+git@gmail.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: asyncio,cache,caching,celery,decorator,distributed lock,dragonflydb,fastapi,lock,mutex,pool,redis,semaphore
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Information Technology
17
+ Classifier: Intended Audience :: System Administrators
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3 :: Only
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Classifier: Topic :: Software Development
29
+ Classifier: Topic :: Software Development :: Libraries
30
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
31
+ Classifier: Typing :: Typed
32
+ Requires-Python: <4.0,>=3.10
33
+ Requires-Dist: typing-extensions>=4.15.0
34
+ Description-Content-Type: text/markdown
35
+
36
+ <p align="center">
37
+ <a href="https://py-cachify.readthedocs.io/latest/" target="_blank">
38
+ <img src="https://i.imgur.com/kObXEhW.png" alt="header">
39
+ </a>
40
+ <a href="https://opensource.org/licenses/MIT" target="_blank">
41
+ <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
42
+ </a>
43
+ <a href="https://badge.fury.io/py/py-cachify" target="_blank">
44
+ <img src="https://badge.fury.io/py/py-cachify.svg" alt="PyPI version">
45
+ </a>
46
+ <a href="https://pypi.org/project/py-cachify/" target="_blank">
47
+ <img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/py-cachify">
48
+ </a>
49
+ <a href="https://pypi.org/project/py-cachify/" target="_blank">
50
+ <img src="https://img.shields.io/pypi/pyversions/py-cachify.svg?color=%2334D058" alt="supported versions">
51
+ </a>
52
+ <a href="https://coveralls.io/github/EzyGang/py-cachify?branch=main" target="_blank">
53
+ <img src="https://coveralls.io/repos/github/EzyGang/py-cachify/badge.png?branch=main" alt="Coverage Status">
54
+ </a>
55
+ </p>
56
+ <p align="center">
57
+ <a href="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" target="_blank">
58
+ <img src="https://github.com/EzyGang/py-cachify/actions/workflows/checks.yml/badge.svg" alt="Pre-build checks and Tests">
59
+ </a>
60
+ <a href="https://py-cachify.readthedocs.io/en/latest/?badge=latest" target="_blank">
61
+ <img src="https://readthedocs.org/projects/py-cachify/badge/?version=latest" alt="Documentation Status">
62
+ </a>
63
+ <a href="https://sonarcloud.io/summary/new_code?id=EzyGang_py-cachify" target="_blank">
64
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=EzyGang_py-cachify&metric=reliability_rating" alt="Reliability Rating">
65
+ </a>
66
+ </p>
67
+
68
+ ---
69
+
70
+ **Py-Cachify** is a lightweight, backend-agnostic Python library for caching, distributed locking, and resource pool management. Works seamlessly with both sync and async code.
71
+
72
+ Out of the box, it supports **in-memory**, **Redis**, and **DragonflyDB** backends. You can also integrate **any custom backend** by implementing the `SyncClient` or `AsyncClient` protocols.
73
+
74
+ **Documentation**: https://py-cachify.readthedocs.io/latest/
75
+ **Source Code**: https://github.com/EzyGang/py-cachify
76
+ **FastAPI Demo**: https://github.com/EzyGang/py-cachify-fastapi-demo
77
+
78
+ ---
79
+
80
+ ## Table of Contents
81
+
82
+ - [Why py-cachify?](#why-py-cachify)
83
+ - [Installation](#installation)
84
+ - [Quick Start](#quick-start)
85
+ - [Core Features](#core-features)
86
+ - [Caching](#caching)
87
+ - [Distributed Locks](#distributed-locks)
88
+ - [Run Once](#run-once)
89
+ - [Resource Pools](#resource-pools) *(New in 3.1.0)*
90
+ - [Advanced Patterns](#advanced-patterns)
91
+ - [Backend Configuration](#backend-configuration)
92
+ - [API Quick Reference](#api-quick-reference)
93
+ - [Contributing](#contributing)
94
+ - [License](#license)
95
+
96
+ ---
97
+
98
+ ## Why py-cachify?
99
+
100
+ There are many caching libraries for Python—so why choose py-cachify?
101
+
102
+ **🪶 Tiny & Focused** — No bloated dependencies or complex setup. Just install and use.
103
+
104
+ **🔌 Backend Agnostic** — Switch from in-memory (development) to Redis/DragonflyDB (production) by changing one line. Or plug in any custom backend that implements simple protocols.
105
+
106
+ **✨ Minimal, Intuitive Syntax** — Stop wrestling with low-level `get/set` calls. One decorator handles caching, locking, or pool management automatically.
107
+
108
+ **🎯 Decorators That Just Work** — No manual key management, no cache client wiring in every file. Initialize once, decorate everywhere. Both sync and async functions are supported with identical APIs.
109
+
110
+ **🏭 Production Ready** — 100% test coverage, used in commercial projects, fully type-annotated for excellent IDE support.
111
+
112
+ | Feature | What it solves |
113
+ |---------|---------------|
114
+ | **@cached** | Eliminate redundant expensive computations and I/O |
115
+ | **lock / @lock** | Prevent race conditions in distributed systems |
116
+ | **@once** | Ensure background tasks don't overlap (deduplication) |
117
+ | **pool / @pooled** | Control concurrency—rate limiting, connection limits *(v3.1.0)* |
118
+ | **Backend Agnostic** | Switch between in-memory (dev) and Redis (prod) with one line |
119
+ | **Sync + Async** | Same API for both sync and async code |
120
+
121
+ ---
122
+
123
+ ## Installation
124
+
125
+ ### pip
126
+ ```bash
127
+ pip install py-cachify
128
+ ```
129
+
130
+ ### uv
131
+ ```bash
132
+ uv add py-cachify
133
+ ```
134
+
135
+ ### poetry
136
+ ```bash
137
+ poetry add py-cachify
138
+ ```
139
+
140
+ For Redis support, you'll also need:
141
+ ```bash
142
+ pip install redis
143
+ # or
144
+ uv add redis
145
+ # or
146
+ poetry add redis
147
+ ```
148
+
149
+ ---
150
+
151
+ ## Quick Start
152
+
153
+ ```python
154
+ from py_cachify import init_cachify, cached
155
+
156
+ # Initialize once (uses in-memory cache by default)
157
+ init_cachify()
158
+
159
+ @cached(key='user-{user_id}', ttl=300)
160
+ async def get_user(user_id: int) -> dict:
161
+ return await fetch_from_db(user_id)
162
+
163
+ # First call executes the function
164
+ user = await get_user(42)
165
+
166
+ # Subsequent calls return cached result instantly
167
+ user = await get_user(42)
168
+
169
+ # Manually invalidate when needed
170
+ await get_user.reset(user_id=42)
171
+ ```
172
+
173
+ 📖 **[Full Tutorial →](https://py-cachify.readthedocs.io/latest/tutorial/)**
174
+ 📖 **[API Reference →](https://py-cachify.readthedocs.io/latest/reference/init.md)**
175
+
176
+ ---
177
+
178
+ ## Core Features
179
+
180
+ ### Caching
181
+
182
+ Cache function results with dynamic keys and configurable TTL.
183
+
184
+ ```python
185
+ from py_cachify import init_cachify, cached
186
+
187
+ init_cachify(default_cache_ttl=60) # Default 60s when ttl is omitted
188
+
189
+ @cached(key='sum-{a}-{b}', ttl=300) # Custom TTL
190
+ async def sum_two(a: int, b: int) -> int:
191
+ return a + b
192
+
193
+ @cached(key='profile-{user_id}') # Uses default_cache_ttl=60
194
+ async def get_profile(user_id: int) -> dict:
195
+ return await fetch_profile(user_id)
196
+
197
+ @cached(key='flags', ttl=None) # Never expires
198
+ def get_feature_flags() -> dict:
199
+ return load_flags()
200
+ ```
201
+
202
+ **Reset cache manually:**
203
+ ```python
204
+ await sum_two.reset(a=1, b=2) # Clear specific entry
205
+ ```
206
+
207
+ **Custom encoder/decoder** for non-picklable types:
208
+ ```python
209
+ def encode(obj: MyClass) -> dict:
210
+ return {'data': obj.to_dict()}
211
+
212
+ def decode(data: dict) -> MyClass:
213
+ return MyClass.from_dict(data['data'])
214
+
215
+ @cached(key='obj-{id}', enc_dec=(encode, decode))
216
+ def get_obj(id: int) -> MyClass:
217
+ return MyClass(id)
218
+ ```
219
+
220
+ [Full @cached reference →](https://py-cachify.readthedocs.io/latest/reference/cached/)
221
+
222
+ ---
223
+
224
+ ### Distributed Locks
225
+
226
+ Prevent concurrent execution with distributed locks.
227
+
228
+ **Context manager:**
229
+ ```python
230
+ from py_cachify import lock
231
+
232
+ # Async
233
+ async with lock('resource-{id}', nowait=False, timeout=10):
234
+ await process_resource(id)
235
+
236
+ # Sync
237
+ with lock('critical-section'):
238
+ process_data()
239
+
240
+ # Check and force release
241
+ await lock('resource-{id}').is_alocked()
242
+ await lock('resource-{id}').arelease()
243
+ ```
244
+
245
+ **Decorator:**
246
+ ```python
247
+ @lock(key='process-{item_id}', nowait=True)
248
+ async def process_item(item_id: str):
249
+ # Only one execution at a time per item_id
250
+ await do_work(item_id)
251
+
252
+ # Check if locked for specific args
253
+ await process_item.is_locked(item_id='abc')
254
+ await process_item.release(item_id='abc')
255
+ ```
256
+
257
+ [Full lock reference →](https://py-cachify.readthedocs.io/latest/reference/lock/)
258
+
259
+ ---
260
+
261
+ ### Run Once
262
+
263
+ Ensure a function runs only once at a time—useful for background tasks.
264
+
265
+ ```python
266
+ from py_cachify import once
267
+
268
+ @once(key='sync-order-{order_id}', raise_on_locked=False, return_on_locked=None)
269
+ async def sync_order(order_id: str):
270
+ # If another task is already syncing this order, this exits early
271
+ await call_external_api(order_id)
272
+
273
+ @once(key='daily-report', raise_on_locked=True)
274
+ def generate_report():
275
+ # Raises CachifyLockError if already running
276
+ run_expensive_analysis()
277
+ ```
278
+
279
+ Perfect for Celery, Dramatiq, Taskiq, or any task queue to prevent duplicate processing.
280
+
281
+ [Full @once reference →](https://py-cachify.readthedocs.io/latest/reference/once/)
282
+
283
+ ---
284
+
285
+ ### Resource Pools *(New in 3.1.0)*
286
+
287
+ Limit concurrent execution to N at a time—ideal for API rate limits, connection pools, or worker throttling.
288
+
289
+ **Context manager:**
290
+ ```python
291
+ from py_cachify import pool, CachifyPoolFullError
292
+
293
+ async with pool(key='api-pool-{user_id}', max_size=5):
294
+ # Max 5 concurrent API calls per user
295
+ await call_external_api(user_id)
296
+ ```
297
+
298
+ **Decorator with graceful handling:**
299
+ ```python
300
+ from py_cachify import pooled
301
+
302
+ def queue_for_later(*args, **kwargs):
303
+ # Called when pool is full instead of executing
304
+ return {'status': 'queued', 'task_id': kwargs.get('task_id')}
305
+
306
+ @pooled(key='worker-pool', max_size=10, on_full=queue_for_later)
307
+ async def process_task(task_id: str):
308
+ await do_work(task_id)
309
+
310
+ # Check pool occupancy
311
+ occupancy = await process_task.size()
312
+ ```
313
+
314
+ **Raise on full:**
315
+ ```python
316
+ @pooled(key='strict-pool', max_size=3, raise_on_full=True)
317
+ async def strict_task():
318
+ # Raises CachifyPoolFullError when pool is full
319
+ await work()
320
+ ```
321
+
322
+ [Full pool reference →](https://py-cachify.readthedocs.io/latest/reference/pool/)
323
+
324
+ ---
325
+
326
+ ## Advanced Patterns
327
+
328
+ ### Multi-Layer Caching
329
+
330
+ Stack caches for optimal performance—fast in-memory layer over persistent Redis.
331
+
332
+ ```python
333
+ init_cachify(default_cache_ttl=300) # Redis layer
334
+
335
+ # Local in-memory instance with shorter TTL
336
+ local = init_cachify(is_global=False, prefix='L1-', default_cache_ttl=5)
337
+
338
+ @local.cached(key='l1-{user_id}') # Outer: in-memory, 5s
339
+ @cached(key='l2-{user_id}') # Inner: Redis, 5min
340
+ async def get_user(user_id: int):
341
+ return await fetch_user(user_id)
342
+
343
+ # Reset clears both layers
344
+ await get_user.reset(user_id=42)
345
+ ```
346
+
347
+ [Multi-layer tutorial →](https://py-cachify.readthedocs.io/latest/tutorial/cached-decorator/reset-attribute.md)
348
+
349
+ ### Instance-Based Usage
350
+
351
+ Create isolated caches for different subsystems.
352
+
353
+ ```python
354
+ # Global for main app
355
+ init_cachify(prefix='APP-')
356
+
357
+ # Isolated instance for metrics (different prefix, different TTL)
358
+ metrics = init_cachify(is_global=False, prefix='METRICS-', default_cache_ttl=60)
359
+
360
+ @metrics.cached(key='metric-{name}')
361
+ def compute_metric(name: str) -> float:
362
+ return expensive_calculation(name)
363
+ ```
364
+
365
+ ---
366
+
367
+ ## Backend Configuration
368
+
369
+ ### Redis / DragonflyDB
370
+
371
+ ```python
372
+ from py_cachify import init_cachify
373
+ from redis import from_url as redis_from_url
374
+ from redis.asyncio import from_url as async_redis_from_url
375
+
376
+ init_cachify(
377
+ sync_client=redis_from_url('redis://localhost:6379/0'),
378
+ async_client=async_redis_from_url('redis://localhost:6379/0'),
379
+ prefix='APP-',
380
+ default_cache_ttl=300,
381
+ default_lock_expiration=30,
382
+ default_pool_slot_expiration=600, # 10 min for pool slots
383
+ lock_poll_interval=0.1, # Check lock every 100ms when waiting
384
+ )
385
+ ```
386
+
387
+ ### In-Memory (Default)
388
+
389
+ ```python
390
+ from py_cachify import init_cachify
391
+
392
+ # Perfect for development and testing
393
+ init_cachify()
394
+ ```
395
+
396
+ ### Custom Backend
397
+
398
+ Implement `SyncClient` or `AsyncClient` protocols for Memcached, database-backed, or file-based caching.
399
+
400
+ [Custom client guide →](https://py-cachify.readthedocs.io/latest/reference/init.md#custom-clients)
401
+
402
+ ---
403
+
404
+ ## API Quick Reference
405
+
406
+ | Decorator/Class | Purpose | Key Parameters |
407
+ |-----------------|---------|----------------|
408
+ | `@cached(key, ttl, enc_dec)` | Cache function results | `key`: template string, `ttl`: expiration in seconds |
409
+ | `lock(key, nowait, timeout)` | Distributed lock context manager | `nowait`: fail fast, `timeout`: max wait time |
410
+ | `@lock(key, nowait, timeout)` | Lock as decorator | Same as above |
411
+ | `@once(key, raise_on_locked, return_on_locked)` | Prevent concurrent runs | `raise_on_locked`: exception vs skip |
412
+ | `pool(key, max_size, slot_exp)` | Resource pool context manager *(v3.1.0)* | `max_size`: max concurrent, `slot_exp`: slot TTL |
413
+ | `@pooled(key, max_size, on_full, raise_on_full)` | Pool as decorator *(v3.1.0)* | `on_full`: callback when full |
414
+
415
+ [Full API reference →](https://py-cachify.readthedocs.io/latest/reference/init.md)
416
+
417
+ ---
418
+
419
+ ## Contributing
420
+
421
+ If you'd like to contribute, please first discuss changes via [Issues](https://github.com/EzyGang/py-cachify/issues), then submit a PR.
422
+
423
+ ---
424
+
425
+ ## License
426
+
427
+ This project is licensed under the MIT License - see the [LICENSE](https://github.com/EzyGang/py-cachify/blob/main/LICENSE) file for details.