Skip to content

Commit 8b4da10

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 4f69bce commit 8b4da10

7 files changed

Lines changed: 42 additions & 128 deletions

File tree

examples/metrics_example.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,7 @@ def sampled_operation(x):
126126
print(f" Hits: {stats.hits}")
127127
print(f" Misses: {stats.misses}")
128128
print(f" Hit rate: {stats.hit_rate:.1f}%")
129-
print(
130-
" Note: Total calls < 100 due to sampling; hit rate is approximately"
131-
" representative of overall behavior."
132-
)
129+
print(" Note: Total calls < 100 due to sampling; hit rate is approximately representative of overall behavior.")
133130

134131
# Example 4: Comprehensive metrics snapshot
135132
print("\n" + "=" * 60)

src/cachier/core.py

Lines changed: 16 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,7 @@ def _convert_args_kwargs(func, _is_method: bool, args: tuple, kwds: dict) -> dic
9292
param = sig.parameters[param_name]
9393
if param.kind == inspect.Parameter.VAR_POSITIONAL:
9494
var_positional_name = param_name
95-
elif param.kind in (
96-
inspect.Parameter.POSITIONAL_ONLY,
97-
inspect.Parameter.POSITIONAL_OR_KEYWORD
98-
):
95+
elif param.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD):
9996
regular_params.append(param_name)
10097

10198
# Map positional arguments to regular parameters
@@ -250,9 +247,7 @@ def cachier(
250247
# Update parameters with defaults if input is None
251248
backend = _update_with_defaults(backend, "backend")
252249
mongetter = _update_with_defaults(mongetter, "mongetter")
253-
size_limit_bytes = parse_bytes(
254-
_update_with_defaults(entry_size_limit, "entry_size_limit")
255-
)
250+
size_limit_bytes = parse_bytes(_update_with_defaults(entry_size_limit, "entry_size_limit"))
256251

257252
# Create metrics object if enabled
258253
cache_metrics = None
@@ -286,7 +281,7 @@ def cachier(
286281
hash_func=hash_func,
287282
wait_for_calc_timeout=wait_for_calc_timeout,
288283
entry_size_limit=size_limit_bytes,
289-
metrics=cache_metrics
284+
metrics=cache_metrics,
290285
)
291286
elif backend == "sql":
292287
core = _SQLCore(
@@ -367,11 +362,7 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
367362
from .config import _global_params
368363

369364
if ignore_cache or not _global_params.caching_enabled:
370-
return (
371-
func(args[0], **kwargs)
372-
if core.func_is_method
373-
else func(**kwargs)
374-
)
365+
return func(args[0], **kwargs) if core.func_is_method else func(**kwargs)
375366

376367
# Start timing for metrics
377368
start_time = time.perf_counter() if cache_metrics else None
@@ -384,23 +375,17 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
384375
result = _calc_entry(core, key, func, args, kwds, _print)
385376
if cache_metrics:
386377
assert start_time is not None # noqa: S101
387-
cache_metrics.record_latency(
388-
time.perf_counter() - start_time
389-
)
378+
cache_metrics.record_latency(time.perf_counter() - start_time)
390379
return result
391-
if entry is None or (
392-
not entry._completed and not entry._processing
393-
):
380+
if entry is None or (not entry._completed and not entry._processing):
394381
_print("No entry found. No current calc. Calling like a boss.")
395382
if cache_metrics:
396383
cache_metrics.record_miss()
397384
cache_metrics.record_recalculation()
398385
result = _calc_entry(core, key, func, args, kwds, _print)
399386
if cache_metrics:
400387
assert start_time is not None # noqa: S101
401-
cache_metrics.record_latency(
402-
time.perf_counter() - start_time
403-
)
388+
cache_metrics.record_latency(time.perf_counter() - start_time)
404389
return result
405390
_print("Entry found.")
406391
if _allow_none or entry.value is not None:
@@ -421,9 +406,7 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
421406
if cache_metrics:
422407
cache_metrics.record_hit()
423408
assert start_time is not None # noqa: S101
424-
cache_metrics.record_latency(
425-
time.perf_counter() - start_time
426-
)
409+
cache_metrics.record_latency(time.perf_counter() - start_time)
427410
return entry.value
428411
_print("But it is stale... :(")
429412
if cache_metrics:
@@ -433,31 +416,23 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
433416
_print("Returning stale.")
434417
if cache_metrics:
435418
assert start_time is not None # noqa: S101
436-
cache_metrics.record_latency(
437-
time.perf_counter() - start_time
438-
)
419+
cache_metrics.record_latency(time.perf_counter() - start_time)
439420
return entry.value # return stale val
440421
_print("Already calc. Waiting on change.")
441422
try:
442423
result = core.wait_on_entry_calc(key)
443424
if cache_metrics:
444425
assert start_time is not None # noqa: S101
445-
cache_metrics.record_latency(
446-
time.perf_counter() - start_time
447-
)
426+
cache_metrics.record_latency(time.perf_counter() - start_time)
448427
return result
449428
except RecalculationNeeded:
450429
if cache_metrics:
451430
cache_metrics.record_wait_timeout()
452431
cache_metrics.record_recalculation()
453-
result = _calc_entry(
454-
core, key, func, args, kwds, _print
455-
)
432+
result = _calc_entry(core, key, func, args, kwds, _print)
456433
if cache_metrics:
457434
assert start_time is not None # noqa: S101
458-
cache_metrics.record_latency(
459-
time.perf_counter() - start_time
460-
)
435+
cache_metrics.record_latency(time.perf_counter() - start_time)
461436
return result
462437
if _next_time:
463438
_print("Async calc and return stale")
@@ -470,29 +445,23 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
470445
core.mark_entry_not_calculated(key)
471446
if cache_metrics:
472447
assert start_time is not None # noqa: S101
473-
cache_metrics.record_latency(
474-
time.perf_counter() - start_time
475-
)
448+
cache_metrics.record_latency(time.perf_counter() - start_time)
476449
return entry.value
477450
_print("Calling decorated function and waiting")
478451
if cache_metrics:
479452
cache_metrics.record_recalculation()
480453
result = _calc_entry(core, key, func, args, kwds, _print)
481454
if cache_metrics:
482455
assert start_time is not None # noqa: S101
483-
cache_metrics.record_latency(
484-
time.perf_counter() - start_time
485-
)
456+
cache_metrics.record_latency(time.perf_counter() - start_time)
486457
return result
487458
if entry._processing:
488459
_print("No value but being calculated. Waiting.")
489460
try:
490461
result = core.wait_on_entry_calc(key)
491462
if cache_metrics:
492463
assert start_time is not None # noqa: S101
493-
cache_metrics.record_latency(
494-
time.perf_counter() - start_time
495-
)
464+
cache_metrics.record_latency(time.perf_counter() - start_time)
496465
return result
497466
except RecalculationNeeded:
498467
if cache_metrics:
@@ -502,9 +471,7 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
502471
result = _calc_entry(core, key, func, args, kwds, _print)
503472
if cache_metrics:
504473
assert start_time is not None # noqa: S101
505-
cache_metrics.record_latency(
506-
time.perf_counter() - start_time
507-
)
474+
cache_metrics.record_latency(time.perf_counter() - start_time)
508475
return result
509476
_print("No entry found. No current calc. Calling like a boss.")
510477
if cache_metrics:

src/cachier/cores/memory.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ def __init__(
2222
entry_size_limit: Optional[int] = None,
2323
metrics: Optional["CacheMetrics"] = None,
2424
):
25-
super().__init__(
26-
hash_func, wait_for_calc_timeout, entry_size_limit, metrics
27-
)
25+
super().__init__(hash_func, wait_for_calc_timeout, entry_size_limit, metrics)
2826
self.cache: Dict[str, CacheEntry] = {}
2927

3028
def _hash_func_key(self, key: str) -> str:

src/cachier/cores/pickle.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,7 @@ def __init__(
8484
entry_size_limit: Optional[int] = None,
8585
metrics: Optional["CacheMetrics"] = None,
8686
):
87-
super().__init__(
88-
hash_func, wait_for_calc_timeout, entry_size_limit, metrics
89-
)
87+
super().__init__(hash_func, wait_for_calc_timeout, entry_size_limit, metrics)
9088
self._cache_dict: Dict[str, CacheEntry] = {}
9189
self.reload = _update_with_defaults(pickle_reload, "pickle_reload")
9290
self.cache_dir = os.path.expanduser(_update_with_defaults(cache_dir, "cache_dir"))

src/cachier/cores/redis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(
5050
hash_func=hash_func,
5151
wait_for_calc_timeout=wait_for_calc_timeout,
5252
entry_size_limit=entry_size_limit,
53-
metrics=metrics
53+
metrics=metrics,
5454
)
5555
if redis_client is None:
5656
raise MissingRedisClient("must specify ``redis_client`` when using the redis core")

src/cachier/exporters/prometheus.py

Lines changed: 16 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,7 @@ def collect(self):
166166
func_name,
167167
func,
168168
) in self.exporter._registered_functions.items():
169-
if (
170-
not hasattr(func, "metrics")
171-
or func.metrics is None
172-
):
169+
if not hasattr(func, "metrics") or func.metrics is None:
173170
continue
174171

175172
stats = func.metrics.get_stats()
@@ -178,13 +175,9 @@ def collect(self):
178175
misses.add_metric([func_name], stats.misses)
179176
hit_rate.add_metric([func_name], stats.hit_rate)
180177
stale_hits.add_metric([func_name], stats.stale_hits)
181-
recalculations.add_metric(
182-
[func_name], stats.recalculations
183-
)
178+
recalculations.add_metric([func_name], stats.recalculations)
184179
entry_count.add_metric([func_name], stats.entry_count)
185-
cache_size.add_metric(
186-
[func_name], stats.total_size_bytes
187-
)
180+
cache_size.add_metric([func_name], stats.total_size_bytes)
188181

189182
yield hits
190183
yield misses
@@ -227,8 +220,7 @@ def register_function(self, func: Callable) -> None:
227220
"""
228221
if not hasattr(func, "metrics") or func.metrics is None:
229222
raise ValueError(
230-
f"Function {func.__name__} does not have metrics enabled. "
231-
"Use @cachier(enable_metrics=True)"
223+
f"Function {func.__name__} does not have metrics enabled. Use @cachier(enable_metrics=True)"
232224
)
233225

234226
with self._lock:
@@ -274,9 +266,7 @@ def _generate_text_metrics(self) -> str:
274266
if not hasattr(func, "metrics") or func.metrics is None:
275267
continue
276268
stats = func.metrics.get_stats()
277-
lines.append(
278-
f'cachier_cache_hits_total{{function="{func_name}"}} {stats.hits}'
279-
)
269+
lines.append(f'cachier_cache_hits_total{{function="{func_name}"}} {stats.hits}')
280270

281271
# Misses
282272
lines.append("")
@@ -288,9 +278,7 @@ def _generate_text_metrics(self) -> str:
288278
if not hasattr(func, "metrics") or func.metrics is None:
289279
continue
290280
stats = func.metrics.get_stats()
291-
lines.append(
292-
f'cachier_cache_misses_total{{function="{func_name}"}} {stats.misses}'
293-
)
281+
lines.append(f'cachier_cache_misses_total{{function="{func_name}"}} {stats.misses}')
294282

295283
# Hit rate
296284
lines.append("")
@@ -302,25 +290,19 @@ def _generate_text_metrics(self) -> str:
302290
if not hasattr(func, "metrics") or func.metrics is None:
303291
continue
304292
stats = func.metrics.get_stats()
305-
lines.append(
306-
f'cachier_cache_hit_rate{{function="{func_name}"}} {stats.hit_rate:.2f}'
307-
)
293+
lines.append(f'cachier_cache_hit_rate{{function="{func_name}"}} {stats.hit_rate:.2f}')
308294

309295
# Average latency
310296
lines.append("")
311-
lines.append(
312-
"# HELP cachier_avg_latency_ms Average cache operation latency in milliseconds"
313-
)
297+
lines.append("# HELP cachier_avg_latency_ms Average cache operation latency in milliseconds")
314298
lines.append("# TYPE cachier_avg_latency_ms gauge")
315299

316300
with self._lock:
317301
for func_name, func in self._registered_functions.items():
318302
if not hasattr(func, "metrics") or func.metrics is None:
319303
continue
320304
stats = func.metrics.get_stats()
321-
lines.append(
322-
f'cachier_avg_latency_ms{{function="{func_name}"}} {stats.avg_latency_ms:.4f}'
323-
)
305+
lines.append(f'cachier_avg_latency_ms{{function="{func_name}"}} {stats.avg_latency_ms:.4f}')
324306

325307
# Stale hits
326308
lines.append("")
@@ -332,25 +314,19 @@ def _generate_text_metrics(self) -> str:
332314
if not hasattr(func, "metrics") or func.metrics is None:
333315
continue
334316
stats = func.metrics.get_stats()
335-
lines.append(
336-
f'cachier_stale_hits_total{{function="{func_name}"}} {stats.stale_hits}'
337-
)
317+
lines.append(f'cachier_stale_hits_total{{function="{func_name}"}} {stats.stale_hits}')
338318

339319
# Recalculations
340320
lines.append("")
341-
lines.append(
342-
"# HELP cachier_recalculations_total Total cache recalculations"
343-
)
321+
lines.append("# HELP cachier_recalculations_total Total cache recalculations")
344322
lines.append("# TYPE cachier_recalculations_total counter")
345323

346324
with self._lock:
347325
for func_name, func in self._registered_functions.items():
348326
if not hasattr(func, "metrics") or func.metrics is None:
349327
continue
350328
stats = func.metrics.get_stats()
351-
lines.append(
352-
f'cachier_recalculations_total{{function="{func_name}"}} {stats.recalculations}'
353-
)
329+
lines.append(f'cachier_recalculations_total{{function="{func_name}"}} {stats.recalculations}')
354330

355331
# Entry count
356332
lines.append("")
@@ -362,31 +338,23 @@ def _generate_text_metrics(self) -> str:
362338
if not hasattr(func, "metrics") or func.metrics is None:
363339
continue
364340
stats = func.metrics.get_stats()
365-
lines.append(
366-
f'cachier_entry_count{{function="{func_name}"}} {stats.entry_count}'
367-
)
341+
lines.append(f'cachier_entry_count{{function="{func_name}"}} {stats.entry_count}')
368342

369343
# Cache size
370344
lines.append("")
371-
lines.append(
372-
"# HELP cachier_cache_size_bytes Total cache size in bytes"
373-
)
345+
lines.append("# HELP cachier_cache_size_bytes Total cache size in bytes")
374346
lines.append("# TYPE cachier_cache_size_bytes gauge")
375347

376348
with self._lock:
377349
for func_name, func in self._registered_functions.items():
378350
if not hasattr(func, "metrics") or func.metrics is None:
379351
continue
380352
stats = func.metrics.get_stats()
381-
lines.append(
382-
f'cachier_cache_size_bytes{{function="{func_name}"}} {stats.total_size_bytes}'
383-
)
353+
lines.append(f'cachier_cache_size_bytes{{function="{func_name}"}} {stats.total_size_bytes}')
384354

385355
# Size limit rejections
386356
lines.append("")
387-
lines.append(
388-
"# HELP cachier_size_limit_rejections_total Entries rejected due to size limit"
389-
)
357+
lines.append("# HELP cachier_size_limit_rejections_total Entries rejected due to size limit")
390358
lines.append("# TYPE cachier_size_limit_rejections_total counter")
391359

392360
with self._lock:

0 commit comments

Comments
 (0)