pycacheable 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Leonardo Pinho
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: pycacheable
3
+ Version: 0.1.0
4
+ Summary: Decorator de cache para funções e métodos Python, com backends InMemory e SQLite, TTL configurável e hash estável de parâmetros.
5
+ Author-email: Leonardo Pinho <contato@leonardopinho.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Leonardo Pinho
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in
18
+ all copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ THE SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/leonardopinho/pycacheable
29
+ Project-URL: Repository, https://github.com/leonardopinho/pycacheable
30
+ Project-URL: Issues, https://github.com/leonardopinho/pycacheable/issues
31
+ Keywords: cache,decorator,sqlite,python,performance,memoization,pycharm
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.9
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Topic :: Software Development :: Libraries
41
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
+ Classifier: Operating System :: OS Independent
43
+ Requires-Python: >=3.9
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: typing-extensions>=4.0.0
47
+ Dynamic: license-file
48
+
49
+ # PyCacheable
50
+
51
+ Decorator de cache para métodos e funções Python com backends em memória e SQLite — serialização automática, hash estável de parâmetros, suporte a instância/estado e arquitetura plugável.
52
+
53
+ ---
54
+
55
+ ## Problema
56
+
57
+ Em muitos aplicativos Python existem métodos que:
58
+
59
+ - fazem consultas repetidas ao banco de dados ou a APIs externas;
60
+ - recebem os mesmos parâmetros múltiplas vezes;
61
+ - repetem trabalho caro de CPU ou I/O;
62
+ - ou seja: fazem **o mesmo trabalho mais de uma vez**, desperdiçando tempo e recursos.
63
+
64
+ Sem um mecanismo de cache, cada chamada resulta em reexecução completa, levando a latências elevadas, carga extra no banco/serviço, e experiência de usuário piorada.
65
+
66
+ ---
67
+
68
+ ## Solução
69
+
70
+ A biblioteca fornece:
71
+
72
+ - Um decorator `@cacheable(...)` que envolve funções ou métodos, gera uma **chave estável** a partir dos parâmetros (serialização canônica + sha256);
73
+ - Suporte a backends:
74
+ - `InMemoryCache`: cache volátil em memória com LRU + TTL.
75
+ - `SQLiteCache`: cache persistente em disco (SQLite) com TTL, ideal para entre execuções ou processos;
76
+ - Logs claros de fluxo: HIT / MISS / EXPIRE — permitindo entender se o cache está funcionando;
77
+ - Métodos auxiliares:
78
+ - `.cache_clear()`, `.cache_info()` no wrapper para inspeção/manutenção;
79
+
80
+ ---
81
+
82
+ ## Como usar
83
+
84
+ ```python
85
+ from src.pycacheable.backend_sqlite import SQLiteCache
86
+ from src.pycacheable.backend_memory import InMemoryCache
87
+ from src.pycacheable.cacheable import cacheable
88
+
89
+ mem = InMemoryCache(max_entries=512)
90
+ disk = SQLiteCache(path="./.cache/myapp.sqlite")
91
+
92
+
93
+ class Repo:
94
+ @cacheable(ttl=60, backend=mem)
95
+ def get_user(self, user_id: int) -> dict:
96
+ # consulta cara ao banco
97
+ return {"user_id": user_id, "name": f"user{user_id}"}
98
+
99
+ @cacheable(ttl=300, backend=disk)
100
+ def get_orders(self, user_id: int, status: str = "open") -> list:
101
+ return [{"order_id": 101, "user_id": user_id, "status": status}]
102
+
103
+
104
+ repo = Repo()
105
+ u1 = repo.get_user(42) # MISS → executa consulta
106
+ u2 = repo.get_user(42) # HIT → retorna cache, consulta não é executada
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Benefícios
112
+
113
+ - Menor latência em chamadas repetidas (hit quase instantâneo).
114
+ - Menor carga no banco/serviço, menos I/O repetido.
115
+ - Persistência local (via SQLite) permite cache entre reinícios/processos.
116
+ - Transparente para o usuário da função — apenas aplicar o decorator.
117
+ - Logs e métricas ajudam a monitorar impacto real.
118
+
119
+ ---
120
+
121
+ ## Quando usar
122
+
123
+ - Funções/métodos com **resultado determinístico** (mesmos parâmetros → mesmo resultado)
124
+ - Consultas idempotentes e repetidas
125
+ - Cálculos caros de CPU ou I/O
126
+ - Cenários onde latência importa e repetição deve ser evitada
127
+
128
+ ---
129
+
130
+ ## Considerações e limites
131
+
132
+ - O cache evita reexecuções **somente** se os parâmetros para o método forem os mesmos e serializáveis.
133
+ - Se o método depende de estados mutáveis fora dos parâmetros (ex.: `self.some_state`), você deve usar `include_self=True` ou custom `key_fn`.
134
+ - TTL é usado para expiração — resultados podem ficar “stale” se parâmetros ou contexto mudarem sem mudar a chave.
135
+ - Embora o backend SQLite seja persistente, ele **não substitui** um cache distribuído (ex.: Redis) em cenários multi‑processo/semi‑distribuídos.
136
+
137
+ ---
138
+
139
+ ## Benchmarks
140
+
141
+ Veja resultados reais que medem MISS vs HIT:
142
+
143
+ | Backend | MISS (s) | HIT (s) | Speedup | Calls |
144
+ |----------|-----------|----------|----------|--------|
145
+ | RAW | 0.6827 | — | — | — |
146
+ | InMemory | 0.6630 | 0.000113 | ~5 870× | 1 |
147
+ | SQLite | 0.7157 | 0.000098 | ~7 300× | 1 |
148
+
149
+ O cache reduz o tempo de execução de ~0.68 s para ~0.0001 s — um **speedup superior a 5 000×**.
150
+
151
+ ---
152
+
153
+ ## Próximos passos
154
+
155
+ - Suporte a funções `async def` (decorator awaitable)
156
+ - Backend Redis / LMDB para cenários distribuídos
157
+ - Métricas e integração com Prometheus
158
+
159
+ ---
160
+
161
+ ## Licença
162
+
163
+ MIT License — veja o arquivo `LICENSE` para detalhes.
@@ -0,0 +1,115 @@
1
+ # PyCacheable
2
+
3
+ Decorator de cache para métodos e funções Python com backends em memória e SQLite — serialização automática, hash estável de parâmetros, suporte a instância/estado e arquitetura plugável.
4
+
5
+ ---
6
+
7
+ ## Problema
8
+
9
+ Em muitos aplicativos Python existem métodos que:
10
+
11
+ - fazem consultas repetidas ao banco de dados ou a APIs externas;
12
+ - recebem os mesmos parâmetros múltiplas vezes;
13
+ - repetem trabalho caro de CPU ou I/O;
14
+ - ou seja: fazem **o mesmo trabalho mais de uma vez**, desperdiçando tempo e recursos.
15
+
16
+ Sem um mecanismo de cache, cada chamada resulta em reexecução completa, levando a latências elevadas, carga extra no banco/serviço, e experiência de usuário piorada.
17
+
18
+ ---
19
+
20
+ ## Solução
21
+
22
+ A biblioteca fornece:
23
+
24
+ - Um decorator `@cacheable(...)` que envolve funções ou métodos, gera uma **chave estável** a partir dos parâmetros (serialização canônica + sha256);
25
+ - Suporte a backends:
26
+ - `InMemoryCache`: cache volátil em memória com LRU + TTL.
27
+ - `SQLiteCache`: cache persistente em disco (SQLite) com TTL, ideal para entre execuções ou processos;
28
+ - Logs claros de fluxo: HIT / MISS / EXPIRE — permitindo entender se o cache está funcionando;
29
+ - Métodos auxiliares:
30
+ - `.cache_clear()`, `.cache_info()` no wrapper para inspeção/manutenção;
31
+
32
+ ---
33
+
34
+ ## Como usar
35
+
36
+ ```python
37
+ from src.pycacheable.backend_sqlite import SQLiteCache
38
+ from src.pycacheable.backend_memory import InMemoryCache
39
+ from src.pycacheable.cacheable import cacheable
40
+
41
+ mem = InMemoryCache(max_entries=512)
42
+ disk = SQLiteCache(path="./.cache/myapp.sqlite")
43
+
44
+
45
+ class Repo:
46
+ @cacheable(ttl=60, backend=mem)
47
+ def get_user(self, user_id: int) -> dict:
48
+ # consulta cara ao banco
49
+ return {"user_id": user_id, "name": f"user{user_id}"}
50
+
51
+ @cacheable(ttl=300, backend=disk)
52
+ def get_orders(self, user_id: int, status: str = "open") -> list:
53
+ return [{"order_id": 101, "user_id": user_id, "status": status}]
54
+
55
+
56
+ repo = Repo()
57
+ u1 = repo.get_user(42) # MISS → executa consulta
58
+ u2 = repo.get_user(42) # HIT → retorna cache, consulta não é executada
59
+ ```
60
+
61
+ ---
62
+
63
+ ## Benefícios
64
+
65
+ - Menor latência em chamadas repetidas (hit quase instantâneo).
66
+ - Menor carga no banco/serviço, menos I/O repetido.
67
+ - Persistência local (via SQLite) permite cache entre reinícios/processos.
68
+ - Transparente para o usuário da função — apenas aplicar o decorator.
69
+ - Logs e métricas ajudam a monitorar impacto real.
70
+
71
+ ---
72
+
73
+ ## Quando usar
74
+
75
+ - Funções/métodos com **resultado determinístico** (mesmos parâmetros → mesmo resultado)
76
+ - Consultas idempotentes e repetidas
77
+ - Cálculos caros de CPU ou I/O
78
+ - Cenários onde latência importa e repetição deve ser evitada
79
+
80
+ ---
81
+
82
+ ## Considerações e limites
83
+
84
+ - O cache evita reexecuções **somente** se os parâmetros para o método forem os mesmos e serializáveis.
85
+ - Se o método depende de estados mutáveis fora dos parâmetros (ex.: `self.some_state`), você deve usar `include_self=True` ou custom `key_fn`.
86
+ - TTL é usado para expiração — resultados podem ficar “stale” se parâmetros ou contexto mudarem sem mudar a chave.
87
+ - Embora o backend SQLite seja persistente, ele **não substitui** um cache distribuído (ex.: Redis) em cenários multi‑processo/semi‑distribuídos.
88
+
89
+ ---
90
+
91
+ ## Benchmarks
92
+
93
+ Veja resultados reais que medem MISS vs HIT:
94
+
95
+ | Backend | MISS (s) | HIT (s) | Speedup | Calls |
96
+ |----------|-----------|----------|----------|--------|
97
+ | RAW | 0.6827 | — | — | — |
98
+ | InMemory | 0.6630 | 0.000113 | ~5 870× | 1 |
99
+ | SQLite | 0.7157 | 0.000098 | ~7 300× | 1 |
100
+
101
+ O cache reduz o tempo de execução de ~0.68 s para ~0.0001 s — um **speedup superior a 5 000×**.
102
+
103
+ ---
104
+
105
+ ## Próximos passos
106
+
107
+ - Suporte a funções `async def` (decorator awaitable)
108
+ - Backend Redis / LMDB para cenários distribuídos
109
+ - Métricas e integração com Prometheus
110
+
111
+ ---
112
+
113
+ ## Licença
114
+
115
+ MIT License — veja o arquivo `LICENSE` para detalhes.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "pycacheable"
3
+ version = "0.1.0"
4
+ description = "Decorator de cache para funções e métodos Python, com backends InMemory e SQLite, TTL configurável e hash estável de parâmetros."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Leonardo Pinho", email = "contato@leonardopinho.com" }
8
+ ]
9
+ license = { file = "LICENSE" }
10
+ requires-python = ">=3.9"
11
+ keywords = ["cache", "decorator", "sqlite", "python", "performance", "memoization", "pycharm"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.9",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Software Development :: Libraries",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ "Operating System :: OS Independent",
24
+ ]
25
+
26
+ dependencies = [
27
+ "typing-extensions >=4.0.0",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/leonardopinho/pycacheable"
32
+ Repository = "https://github.com/leonardopinho/pycacheable"
33
+ Issues = "https://github.com/leonardopinho/pycacheable/issues"
34
+
35
+ [build-system]
36
+ requires = ["setuptools>=68.0", "wheel"]
37
+ build-backend = "setuptools.build_meta"
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["src"]
41
+ include = ["pycacheable*"]
42
+ exclude = ["tests", "benchmarks"]
43
+
44
+ [tool.setuptools]
45
+ package-dir = {"" = "src"}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,48 @@
1
+ import pickle
2
+ import threading
3
+ import time
4
+ from typing import Any, Dict, Optional, Tuple, OrderedDict
5
+
6
+ from src.pycacheable.cache_base import CacheBase
7
+
8
+
9
+ class InMemoryCache(CacheBase):
10
+ def __init__(self, max_entries: int = 1024):
11
+ self._store: "OrderedDict[str, Tuple[float, bytes]]" = OrderedDict()
12
+ self._lock = threading.RLock()
13
+ self._max_entries = max_entries
14
+
15
+ def get(self, key: str) -> Tuple[bool, Any, str]:
16
+ with self._lock:
17
+ entry = self._store.get(key)
18
+ now = time.time()
19
+ if not entry:
20
+ return False, None, "MISS"
21
+ expire_at, payload = entry
22
+ if expire_at and expire_at < now:
23
+ self._store.pop(key, None)
24
+ return False, None, "EXPIRE"
25
+
26
+ self._store.move_to_end(key)
27
+ return True, pickle.loads(payload), "HIT"
28
+
29
+ def set(self, key: str, value: Any, ttl_seconds: Optional[int]):
30
+ with self._lock:
31
+ expire_at = (time.time() + ttl_seconds) if ttl_seconds else 0.0
32
+ payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
33
+ self._store[key] = (expire_at, payload)
34
+ self._store.move_to_end(key)
35
+ while len(self._store) > self._max_entries:
36
+ self._store.popitem(last=False)
37
+
38
+ def clear(self):
39
+ with self._lock:
40
+ self._store.clear()
41
+
42
+ def info(self) -> Dict[str, Any]:
43
+ with self._lock:
44
+ return {
45
+ "backend": "InMemoryCache",
46
+ "size": len(self._store),
47
+ "max_entries": self._max_entries,
48
+ }
@@ -0,0 +1,70 @@
1
+ import os
2
+ import pickle
3
+ import sqlite3
4
+ import threading
5
+ import time
6
+ from typing import Any, Dict, Optional, Tuple
7
+
8
+ from src.pycacheable.cache_base import CacheBase
9
+
10
+
11
+ class SQLiteCache(CacheBase):
12
+ def __init__(self, path: str):
13
+ self._path = path
14
+ self._lock = threading.RLock()
15
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
16
+
17
+ with self._conn() as conn:
18
+ conn.execute("""
19
+ CREATE TABLE IF NOT EXISTS cache
20
+ (
21
+ k
22
+ TEXT
23
+ PRIMARY
24
+ KEY,
25
+ expire_at
26
+ REAL,
27
+ v
28
+ BLOB
29
+ )
30
+ """)
31
+
32
+ conn.execute("PRAGMA journal_mode=WAL;")
33
+
34
+ def _conn(self):
35
+ return sqlite3.connect(self._path, timeout=30, isolation_level=None)
36
+
37
+ def get(self, key: str) -> Tuple[bool, Any, str]:
38
+ with self._lock, self._conn() as conn:
39
+ row = conn.execute("SELECT expire_at, v FROM cache WHERE k=?", (key,)).fetchone()
40
+ now = time.time()
41
+ if not row:
42
+ return False, None, "MISS"
43
+ expire_at, blob = row
44
+ if expire_at and expire_at < now:
45
+ conn.execute("DELETE FROM cache WHERE k=?", (key,))
46
+ return False, None, "EXPIRE"
47
+ return True, pickle.loads(blob), "HIT"
48
+
49
+ def set(self, key: str, value: Any, ttl_seconds: Optional[int]):
50
+ expire_at = (time.time() + ttl_seconds) if ttl_seconds else 0.0
51
+ blob = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
52
+ with self._lock, self._conn() as conn:
53
+ conn.execute(
54
+ "REPLACE INTO cache (k, expire_at, v) VALUES (?, ?, ?)",
55
+ (key, expire_at, sqlite3.Binary(blob))
56
+ )
57
+
58
+ def clear(self):
59
+ with self._lock, self._conn() as conn:
60
+ conn.execute("DELETE FROM cache")
61
+
62
+ def info(self) -> Dict[str, Any]:
63
+ with self._lock, self._conn() as conn:
64
+ row = conn.execute("SELECT COUNT(*) FROM cache").fetchone()
65
+ size = int(row[0]) if row else 0
66
+ return {
67
+ "backend": "SQLiteCache",
68
+ "size": size,
69
+ "path": self._path,
70
+ }
@@ -0,0 +1,19 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class CacheBase(ABC):
5
+ @abstractmethod
6
+ def get(self, **args):
7
+ pass
8
+
9
+ @abstractmethod
10
+ def set(self, **args):
11
+ pass
12
+
13
+ @abstractmethod
14
+ def clear(self, **args):
15
+ pass
16
+
17
+ @abstractmethod
18
+ def info(self, **args):
19
+ pass
@@ -0,0 +1,53 @@
1
+ import functools
2
+ from typing import Any, Callable, Dict, Optional, Tuple
3
+
4
+ from src.pycacheable.backend_sqlite import SQLiteCache
5
+ from src.pycacheable.hashing import _build_key_from_call
6
+
7
+
8
+ def cacheable(
9
+ ttl: Optional[int] = 300,
10
+ backend: Optional[object] = None,
11
+ *,
12
+ include_self: bool = False,
13
+ key_fn: Optional[Callable[[Callable, Tuple[Any, ...], Dict[str, Any]], str]] = None,
14
+ logger: Optional[Callable[[str], None]] = None,
15
+ backend_factory: Optional[Callable[..., object]] = None,
16
+ ):
17
+ default_backend = backend or SQLiteCache(path="./.cache/db.sqlite3")
18
+
19
+ def decorator(func: Callable):
20
+ @functools.wraps(func)
21
+ def wrapper(*args, **kwargs):
22
+ be = getattr(wrapper, "cache_backend", None)
23
+ if be is None and backend_factory is not None:
24
+ try:
25
+ be = backend_factory(*args, **kwargs)
26
+ except TypeError:
27
+ be = backend_factory(args[0]) if args else None
28
+ if be is None:
29
+ be = default_backend
30
+
31
+ key = (key_fn(func, args, kwargs)
32
+ if key_fn else _build_key_from_call(func, args, kwargs, include_self))
33
+
34
+ hit, value, status = be.get(key)
35
+ if hit:
36
+ if logger: logger(f"[CACHE {status}] {func.__qualname__} {key[:10]}…")
37
+ return value
38
+
39
+ if logger: logger(f"[CACHE {status}] {func.__qualname__} {key[:10]}… -> calling")
40
+ result = func(*args, **kwargs)
41
+ try:
42
+ be.set(key, result, ttl)
43
+ if logger: logger(f"[CACHE SET] {func.__qualname__} {key[:10]}… ttl={ttl}")
44
+ except Exception as e:
45
+ if logger: logger(f"[CACHE ERROR SET] {func.__qualname__}: {e}")
46
+ return result
47
+
48
+ wrapper.cache_backend = default_backend
49
+ wrapper.cache_clear = lambda: wrapper.cache_backend.clear()
50
+ wrapper.cache_info = lambda: wrapper.cache_backend.info()
51
+ return wrapper
52
+
53
+ return decorator
@@ -0,0 +1,109 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime as dt
4
+ import decimal
5
+ import enum
6
+ import hashlib
7
+ import inspect
8
+ import json
9
+ import pathlib
10
+ import pickle
11
+ import uuid
12
+ from typing import Any, Mapping, Iterable
13
+ from typing import Callable, Dict, Tuple
14
+
15
+
16
+ def _to_canonical(obj: Any) -> Any:
17
+ if obj is None or isinstance(obj, (bool, int, float, str)):
18
+ return obj
19
+
20
+ if isinstance(obj, decimal.Decimal):
21
+ return str(obj)
22
+ if isinstance(obj, uuid.UUID):
23
+ return str(obj)
24
+
25
+ if isinstance(obj, (dt.datetime, dt.date, dt.time)):
26
+ if isinstance(obj, dt.datetime):
27
+ if obj.tzinfo is None:
28
+ obj = obj.replace(tzinfo=dt.timezone.utc) # padroniza se vier naive
29
+ return obj.astimezone(dt.timezone.utc).isoformat(timespec="microseconds")
30
+ if isinstance(obj, dt.date):
31
+ return obj.isoformat()
32
+ if isinstance(obj, dt.time):
33
+ if obj.tzinfo is None:
34
+ obj = obj.replace(tzinfo=dt.timezone.utc)
35
+ return obj.isoformat(timespec="microseconds")
36
+
37
+ if isinstance(obj, pathlib.Path):
38
+ return str(obj)
39
+ if isinstance(obj, enum.Enum):
40
+ return obj.value if isinstance(obj.value, (str, int, float, bool)) else obj.name
41
+
42
+ if isinstance(obj, set):
43
+ return sorted(_to_canonical(x) for x in obj)
44
+ if isinstance(obj, tuple):
45
+ return ["__tuple__", *(_to_canonical(x) for x in obj)] # preserva semântica
46
+
47
+ if isinstance(obj, Mapping):
48
+ return {str(k): _to_canonical(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}
49
+
50
+ if isinstance(obj, Iterable) and not isinstance(obj, (str, bytes, bytearray)):
51
+ return [_to_canonical(x) for x in obj]
52
+
53
+ if isinstance(obj, (bytes, bytearray, memoryview)):
54
+ return {"__bytes__": bytes(obj).hex()}
55
+
56
+ try:
57
+ import numpy as np # type: ignore
58
+ if isinstance(obj, (np.generic,)): # np.int64, np.float32 etc.
59
+ return obj.item()
60
+ if isinstance(obj, (np.ndarray,)):
61
+ return {"__ndarray__": obj.tolist(), "dtype": str(obj.dtype), "shape": obj.shape}
62
+ except Exception:
63
+ pass
64
+
65
+ return {"__type__": type(obj).__name__, "__repr__": repr(obj)}
66
+
67
+
68
+ def _json_canonical_dumps(payload: Any) -> bytes:
69
+ canon = _to_canonical(payload)
70
+ return json.dumps(canon, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
71
+
72
+
73
+ class EnhancedJSONEncoder(json.JSONEncoder):
74
+ def default(self, o: Any):
75
+ try:
76
+ return {"__type__": type(o).__name__, "__repr__": repr(o)}
77
+ except Exception:
78
+ return super().default(o)
79
+
80
+
81
+ def _json_dumps_canonical(obj: Any) -> bytes:
82
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"), cls=EnhancedJSONEncoder).encode("utf-8")
83
+
84
+
85
+ def _stable_hash(payload: Any) -> str:
86
+ try:
87
+ data = _json_canonical_dumps(payload)
88
+ except Exception:
89
+ data = pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)
90
+
91
+ return hashlib.sha256(data).hexdigest()
92
+
93
+
94
+ def _build_key_from_call(func: Callable, args: Tuple[Any, ...], kwargs: Dict[str, Any], include_self: bool) -> str:
95
+ sig = inspect.signature(func)
96
+ bound = sig.bind_partial(*args, **kwargs)
97
+ bound.apply_defaults()
98
+ items = dict(bound.arguments)
99
+
100
+ if not include_self:
101
+ items.pop("self", None)
102
+ items.pop("cls", None)
103
+
104
+ key_payload = {
105
+ "fn": f"{func.__module__}.{func.__qualname__}",
106
+ "params": items,
107
+ }
108
+
109
+ return _stable_hash(key_payload)
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: pycacheable
3
+ Version: 0.1.0
4
+ Summary: Decorator de cache para funções e métodos Python, com backends InMemory e SQLite, TTL configurável e hash estável de parâmetros.
5
+ Author-email: Leonardo Pinho <contato@leonardopinho.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Leonardo Pinho
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in
18
+ all copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ THE SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/leonardopinho/pycacheable
29
+ Project-URL: Repository, https://github.com/leonardopinho/pycacheable
30
+ Project-URL: Issues, https://github.com/leonardopinho/pycacheable/issues
31
+ Keywords: cache,decorator,sqlite,python,performance,memoization,pycharm
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.9
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Topic :: Software Development :: Libraries
41
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
+ Classifier: Operating System :: OS Independent
43
+ Requires-Python: >=3.9
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: typing-extensions>=4.0.0
47
+ Dynamic: license-file
48
+
49
+ # PyCacheable
50
+
51
+ Decorator de cache para métodos e funções Python com backends em memória e SQLite — serialização automática, hash estável de parâmetros, suporte a instância/estado e arquitetura plugável.
52
+
53
+ ---
54
+
55
+ ## Problema
56
+
57
+ Em muitos aplicativos Python existem métodos que:
58
+
59
+ - fazem consultas repetidas ao banco de dados ou a APIs externas;
60
+ - recebem os mesmos parâmetros múltiplas vezes;
61
+ - repetem trabalho caro de CPU ou I/O;
62
+ - ou seja: fazem **o mesmo trabalho mais de uma vez**, desperdiçando tempo e recursos.
63
+
64
+ Sem um mecanismo de cache, cada chamada resulta em reexecução completa, levando a latências elevadas, carga extra no banco/serviço, e experiência de usuário piorada.
65
+
66
+ ---
67
+
68
+ ## Solução
69
+
70
+ A biblioteca fornece:
71
+
72
+ - Um decorator `@cacheable(...)` que envolve funções ou métodos, gera uma **chave estável** a partir dos parâmetros (serialização canônica + sha256);
73
+ - Suporte a backends:
74
+ - `InMemoryCache`: cache volátil em memória com LRU + TTL.
75
+ - `SQLiteCache`: cache persistente em disco (SQLite) com TTL, ideal para entre execuções ou processos;
76
+ - Logs claros de fluxo: HIT / MISS / EXPIRE — permitindo entender se o cache está funcionando;
77
+ - Métodos auxiliares:
78
+ - `.cache_clear()`, `.cache_info()` no wrapper para inspeção/manutenção;
79
+
80
+ ---
81
+
82
+ ## Como usar
83
+
84
+ ```python
85
+ from src.pycacheable.backend_sqlite import SQLiteCache
86
+ from src.pycacheable.backend_memory import InMemoryCache
87
+ from src.pycacheable.cacheable import cacheable
88
+
89
+ mem = InMemoryCache(max_entries=512)
90
+ disk = SQLiteCache(path="./.cache/myapp.sqlite")
91
+
92
+
93
+ class Repo:
94
+ @cacheable(ttl=60, backend=mem)
95
+ def get_user(self, user_id: int) -> dict:
96
+ # consulta cara ao banco
97
+ return {"user_id": user_id, "name": f"user{user_id}"}
98
+
99
+ @cacheable(ttl=300, backend=disk)
100
+ def get_orders(self, user_id: int, status: str = "open") -> list:
101
+ return [{"order_id": 101, "user_id": user_id, "status": status}]
102
+
103
+
104
+ repo = Repo()
105
+ u1 = repo.get_user(42) # MISS → executa consulta
106
+ u2 = repo.get_user(42) # HIT → retorna cache, consulta não é executada
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Benefícios
112
+
113
+ - Menor latência em chamadas repetidas (hit quase instantâneo).
114
+ - Menor carga no banco/serviço, menos I/O repetido.
115
+ - Persistência local (via SQLite) permite cache entre reinícios/processos.
116
+ - Transparente para o usuário da função — apenas aplicar o decorator.
117
+ - Logs e métricas ajudam a monitorar impacto real.
118
+
119
+ ---
120
+
121
+ ## Quando usar
122
+
123
+ - Funções/métodos com **resultado determinístico** (mesmos parâmetros → mesmo resultado)
124
+ - Consultas idempotentes e repetidas
125
+ - Cálculos caros de CPU ou I/O
126
+ - Cenários onde latência importa e repetição deve ser evitada
127
+
128
+ ---
129
+
130
+ ## Considerações e limites
131
+
132
+ - O cache evita reexecuções **somente** se os parâmetros para o método forem os mesmos e serializáveis.
133
+ - Se o método depende de estados mutáveis fora dos parâmetros (ex.: `self.some_state`), você deve usar `include_self=True` ou custom `key_fn`.
134
+ - TTL é usado para expiração — resultados podem ficar “stale” se parâmetros ou contexto mudarem sem mudar a chave.
135
+ - Embora o backend SQLite seja persistente, ele **não substitui** um cache distribuído (ex.: Redis) em cenários multi‑processo/semi‑distribuídos.
136
+
137
+ ---
138
+
139
+ ## Benchmarks
140
+
141
+ Veja resultados reais que medem MISS vs HIT:
142
+
143
+ | Backend | MISS (s) | HIT (s) | Speedup | Calls |
144
+ |----------|-----------|----------|----------|--------|
145
+ | RAW | 0.6827 | — | — | — |
146
+ | InMemory | 0.6630 | 0.000113 | ~5 870× | 1 |
147
+ | SQLite | 0.7157 | 0.000098 | ~7 300× | 1 |
148
+
149
+ O cache reduz o tempo de execução de ~0.68 s para ~0.0001 s — um **speedup superior a 5 000×**.
150
+
151
+ ---
152
+
153
+ ## Próximos passos
154
+
155
+ - Suporte a funções `async def` (decorator awaitable)
156
+ - Backend Redis / LMDB para cenários distribuídos
157
+ - Métricas e integração com Prometheus
158
+
159
+ ---
160
+
161
+ ## Licença
162
+
163
+ MIT License — veja o arquivo `LICENSE` para detalhes.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pycacheable/__init__.py
5
+ src/pycacheable/backend_memory.py
6
+ src/pycacheable/backend_sqlite.py
7
+ src/pycacheable/cache_base.py
8
+ src/pycacheable/cacheable.py
9
+ src/pycacheable/hashing.py
10
+ src/pycacheable.egg-info/PKG-INFO
11
+ src/pycacheable.egg-info/SOURCES.txt
12
+ src/pycacheable.egg-info/dependency_links.txt
13
+ src/pycacheable.egg-info/requires.txt
14
+ src/pycacheable.egg-info/top_level.txt
15
+ tests/test_memory_cache.py
16
+ tests/test_sqlite_cache.py
@@ -0,0 +1 @@
1
+ typing-extensions>=4.0.0
@@ -0,0 +1 @@
1
+ pycacheable
@@ -0,0 +1,49 @@
1
+ import time
2
+ import unittest
3
+
4
+ from src import cacheable, InMemoryCache
5
+
6
+
7
+ class Repository:
8
+ def __init__(self):
9
+ self.calls = 0
10
+ self.backend = InMemoryCache(max_entries=1024)
11
+
12
+ @cacheable(ttl=3, backend=None)
13
+ def get_user_data(self, user_id: int) -> dict:
14
+ self.calls += 1
15
+
16
+ time.sleep(0.05)
17
+
18
+ return {"user_id": user_id, "name": f"user-{user_id}"}
19
+
20
+
21
+ class CacheableTestMemoryCache(unittest.TestCase):
22
+ def setUp(self):
23
+ self.repo = Repository()
24
+ Repository.get_user_data.cache_backend = self.repo.backend
25
+
26
+ def test_memory_cache_hit(self):
27
+ u1 = self.repo.get_user_data(1)
28
+ self.assertEqual(u1["name"], "user-1")
29
+ self.assertEqual(self.repo.calls, 1)
30
+
31
+ u2 = self.repo.get_user_data(1)
32
+ self.assertEqual(u2["name"], "user-1")
33
+ self.assertEqual(self.repo.calls, 1)
34
+
35
+ info = self.repo.backend.info()
36
+ self.assertIn("size", info)
37
+ self.assertGreaterEqual(info["size"], 1)
38
+
39
+ def test_sqlite_cache_expire(self):
40
+ _ = self.repo.get_user_data(2)
41
+ self.assertEqual(self.repo.calls, 1)
42
+
43
+ _ = self.repo.get_user_data(2)
44
+ self.assertEqual(self.repo.calls, 1)
45
+
46
+ time.sleep(3.5)
47
+
48
+ _ = self.repo.get_user_data(2)
49
+ self.assertEqual(self.repo.calls, 2, "Após TTL, método deve ser executado novamente")
@@ -0,0 +1,58 @@
1
+ import os
2
+ import tempfile
3
+ import time
4
+ import unittest
5
+
6
+ from src import SQLiteCache, cacheable
7
+
8
+
9
+ class Repository:
10
+ def __init__(self, db_path: str):
11
+ self.db_path = db_path
12
+ self.calls = 0
13
+ self.backend = SQLiteCache(db_path)
14
+
15
+ @cacheable(ttl=3, backend=None)
16
+ def get_user_data(self, user_id: int) -> dict:
17
+ self.calls += 1
18
+
19
+ time.sleep(0.05)
20
+
21
+ return {"user_id": user_id, "name": f"user-{user_id}"}
22
+
23
+
24
+ class CacheableTestSQLiteCache(unittest.TestCase):
25
+ def setUp(self):
26
+ self.tmpfile = tempfile.NamedTemporaryFile(suffix=".sqlite", delete=False)
27
+ self.tmpfile.close()
28
+ self.repo = Repository(self.tmpfile.name)
29
+
30
+ Repository.get_user_data.cache_backend = self.repo.backend
31
+
32
+ def tearDown(self):
33
+ os.remove(self.tmpfile.name)
34
+
35
+ def test_sqlite_cache_hit(self):
36
+ u1 = self.repo.get_user_data(1)
37
+ self.assertEqual(u1["name"], "user-1")
38
+ self.assertEqual(self.repo.calls, 1)
39
+
40
+ u2 = self.repo.get_user_data(1)
41
+ self.assertEqual(u2["name"], "user-1")
42
+ self.assertEqual(self.repo.calls, 1)
43
+
44
+ info = self.repo.backend.info()
45
+ self.assertIn("size", info)
46
+ self.assertGreaterEqual(info["size"], 1)
47
+
48
+ def test_sqlite_cache_expire(self):
49
+ _ = self.repo.get_user_data(2)
50
+ self.assertEqual(self.repo.calls, 1)
51
+
52
+ _ = self.repo.get_user_data(2)
53
+ self.assertEqual(self.repo.calls, 1)
54
+
55
+ time.sleep(3.5)
56
+
57
+ _ = self.repo.get_user_data(2)
58
+ self.assertEqual(self.repo.calls, 2, "Após TTL, método deve ser executado novamente")