Skip to content

Commit daa5d1a

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 07328a6 commit daa5d1a

3 files changed

Lines changed: 23 additions & 72 deletions

File tree

examples/async_example.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,7 @@ async def fetch_github_user(username: str) -> dict:
6060
"""Fetch GitHub user data with caching."""
6161
print(f" Making API request for {username}...")
6262
async with httpx.AsyncClient() as client:
63-
response = await client.get(
64-
f"https://api.github.com/users/{username}"
65-
)
63+
response = await client.get(f"https://api.github.com/users/{username}")
6664
return response.json()
6765

6866
# First call - makes actual HTTP request

src/cachier/core.py

Lines changed: 21 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,7 @@ async def _function_thread_async(core, key, func, args, kwds):
6565
print(f"Function call failed with the following exception:\n{exc}")
6666

6767

68-
def _calc_entry(
69-
core, key, func, args, kwds, printer=lambda *_: None
70-
) -> Optional[Any]:
68+
def _calc_entry(core, key, func, args, kwds, printer=lambda *_: None) -> Optional[Any]:
7169
core.mark_entry_being_calculated(key)
7270
try:
7371
func_res = func(*args, **kwds)
@@ -79,9 +77,7 @@ def _calc_entry(
7977
core.mark_entry_not_calculated(key)
8078

8179

82-
async def _calc_entry_async(
83-
core, key, func, args, kwds, printer=lambda *_: None
84-
) -> Optional[Any]:
80+
async def _calc_entry_async(core, key, func, args, kwds, printer=lambda *_: None) -> Optional[Any]:
8581
core.mark_entry_being_calculated(key)
8682
try:
8783
func_res = await func(*args, **kwds)
@@ -93,9 +89,7 @@ async def _calc_entry_async(
9389
core.mark_entry_not_calculated(key)
9490

9591

96-
def _convert_args_kwargs(
97-
func, _is_method: bool, args: tuple, kwds: dict
98-
) -> dict:
92+
def _convert_args_kwargs(func, _is_method: bool, args: tuple, kwds: dict) -> dict:
9993
"""Convert mix of positional and keyword arguments to aggregated kwargs."""
10094
# unwrap if the function is functools.partial
10195
if hasattr(func, "func"):
@@ -378,76 +372,48 @@ def _call(*args, max_age: Optional[timedelta] = None, **kwds):
378372
_print("No entry found. No current calc. Calling like a boss.")
379373
return _calc_entry(core, key, func, args, kwds, _print)
380374

381-
async def _call_async(
382-
*args, max_age: Optional[timedelta] = None, **kwds
383-
):
375+
async def _call_async(*args, max_age: Optional[timedelta] = None, **kwds):
384376
# NOTE: For async functions, wait_for_calc_timeout is not honored.
385377
# Instead of blocking the event loop waiting for concurrent
386378
# calculations, async functions will recalculate in parallel.
387379
# This avoids deadlocks and maintains async efficiency.
388380
nonlocal allow_none, last_cleanup
389381
_allow_none = _update_with_defaults(allow_none, "allow_none", kwds)
390382
# print('Inside async wrapper for {}.'.format(func.__name__))
391-
ignore_cache = _pop_kwds_with_deprecation(
392-
kwds, "ignore_cache", False
393-
)
394-
overwrite_cache = _pop_kwds_with_deprecation(
395-
kwds, "overwrite_cache", False
396-
)
383+
ignore_cache = _pop_kwds_with_deprecation(kwds, "ignore_cache", False)
384+
overwrite_cache = _pop_kwds_with_deprecation(kwds, "overwrite_cache", False)
397385
verbose = _pop_kwds_with_deprecation(kwds, "verbose_cache", False)
398386
ignore_cache = kwds.pop("cachier__skip_cache", ignore_cache)
399-
overwrite_cache = kwds.pop(
400-
"cachier__overwrite_cache", overwrite_cache
401-
)
387+
overwrite_cache = kwds.pop("cachier__overwrite_cache", overwrite_cache)
402388
verbose = kwds.pop("cachier__verbose", verbose)
403-
_stale_after = _update_with_defaults(
404-
stale_after, "stale_after", kwds
405-
)
389+
_stale_after = _update_with_defaults(stale_after, "stale_after", kwds)
406390
_next_time = _update_with_defaults(next_time, "next_time", kwds)
407-
_cleanup_flag = _update_with_defaults(
408-
cleanup_stale, "cleanup_stale", kwds
409-
)
410-
_cleanup_interval_val = _update_with_defaults(
411-
cleanup_interval, "cleanup_interval", kwds
412-
)
391+
_cleanup_flag = _update_with_defaults(cleanup_stale, "cleanup_stale", kwds)
392+
_cleanup_interval_val = _update_with_defaults(cleanup_interval, "cleanup_interval", kwds)
413393
# merge args expanded as kwargs and the original kwds
414-
kwargs = _convert_args_kwargs(
415-
func, _is_method=core.func_is_method, args=args, kwds=kwds
416-
)
394+
kwargs = _convert_args_kwargs(func, _is_method=core.func_is_method, args=args, kwds=kwds)
417395

418396
if _cleanup_flag:
419397
now = datetime.now()
420398
with cleanup_lock:
421399
if now - last_cleanup >= _cleanup_interval_val:
422400
last_cleanup = now
423-
_get_executor().submit(
424-
core.delete_stale_entries, _stale_after
425-
)
401+
_get_executor().submit(core.delete_stale_entries, _stale_after)
426402

427403
_print = print if verbose else lambda x: None
428404

429405
# Check current global caching state dynamically
430406
from .config import _global_params
431407

432408
if ignore_cache or not _global_params.caching_enabled:
433-
return (
434-
await func(args[0], **kwargs)
435-
if core.func_is_method
436-
else await func(**kwargs)
437-
)
409+
return await func(args[0], **kwargs) if core.func_is_method else await func(**kwargs)
438410
key, entry = core.get_entry((), kwargs)
439411
if overwrite_cache:
440-
result = await _calc_entry_async(
441-
core, key, func, args, kwds, _print
442-
)
412+
result = await _calc_entry_async(core, key, func, args, kwds, _print)
443413
return result
444-
if entry is None or (
445-
not entry._completed and not entry._processing
446-
):
414+
if entry is None or (not entry._completed and not entry._processing):
447415
_print("No entry found. No current calc. Calling like a boss.")
448-
result = await _calc_entry_async(
449-
core, key, func, args, kwds, _print
450-
)
416+
result = await _calc_entry_async(core, key, func, args, kwds, _print)
451417
return result
452418
_print("Entry found.")
453419
if _allow_none or entry.value is not None:
@@ -457,10 +423,7 @@ async def _call_async(
457423
nonneg_max_age = True
458424
if max_age is not None:
459425
if max_age < ZERO_TIMEDELTA:
460-
_print(
461-
"max_age is negative. "
462-
"Cached result considered stale."
463-
)
426+
_print("max_age is negative. Cached result considered stale.")
464427
nonneg_max_age = False
465428
else:
466429
assert max_age is not None # noqa: S101
@@ -477,9 +440,7 @@ async def _call_async(
477440
_print("Already calc. Recalculating (async - no wait).")
478441
# For async, don't wait - just recalculate
479442
# This avoids blocking the event loop
480-
result = await _calc_entry_async(
481-
core, key, func, args, kwds, _print
482-
)
443+
result = await _calc_entry_async(core, key, func, args, kwds, _print)
483444
return result
484445
if _next_time:
485446
_print("Async calc and return stale")
@@ -488,24 +449,18 @@ async def _call_async(
488449
# Background task will update cache when complete
489450
core.mark_entry_being_calculated(key)
490451
# Use asyncio.create_task for background execution
491-
asyncio.create_task(
492-
_function_thread_async(core, key, func, args, kwds)
493-
)
452+
asyncio.create_task(_function_thread_async(core, key, func, args, kwds))
494453
core.mark_entry_not_calculated(key)
495454
return entry.value
496455
_print("Calling decorated function and waiting")
497-
result = await _calc_entry_async(
498-
core, key, func, args, kwds, _print
499-
)
456+
result = await _calc_entry_async(core, key, func, args, kwds, _print)
500457
return result
501458
if entry._processing:
502459
msg = "No value but being calculated. Recalculating"
503460
_print(f"{msg} (async - no wait).")
504461
# For async, don't wait - just recalculate
505462
# This avoids blocking the event loop
506-
result = await _calc_entry_async(
507-
core, key, func, args, kwds, _print
508-
)
463+
result = await _calc_entry_async(core, key, func, args, kwds, _print)
509464
return result
510465
_print("No entry found. No current calc. Calling like a boss.")
511466
return await _calc_entry_async(core, key, func, args, kwds, _print)

tests/test_async_core.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,7 @@ async def test_uses_cache_before_expiry(self):
116116
"""Test that cache is used before stale_after expiry."""
117117
call_count = 0
118118

119-
@cachier(
120-
backend="memory", stale_after=timedelta(seconds=1), next_time=False
121-
)
119+
@cachier(backend="memory", stale_after=timedelta(seconds=1), next_time=False)
122120
async def async_func(x):
123121
nonlocal call_count
124122
call_count += 1

0 commit comments

Comments
 (0)