Skip to content

Commit

Permalink
Temp commit
Browse files Browse the repository at this point in the history
  • Loading branch information
GigantPro committed Jul 29, 2023
1 parent 981cce0 commit 0ff6277
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
59 changes: 59 additions & 0 deletions frozenclass/cache.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from pathlib import Path
from typing import Any, Callable
from datetime import time, datetime, timedelta

from .auto_freeze import AutoFreeze

__all__ = ('CacheController',)


class CacheController:
"""The main class of the cache logic. Includes all caches logic"""
Expand Down Expand Up @@ -41,3 +46,57 @@ def cached_func_without_time(*args, **kwargs) -> Any:

return cached_func_with_time if ttl else cached_func_without_time
return wrapper_func

def __init__(self, path_to_temp_files: Path | None, *, no_tmp_files_warn: bool = False) -> None:
self.__tmp_path = path_to_temp_files
if path_to_temp_files:
self.__cache_info = CacheConfig()

else:
self.__cache_info = None

if not no_tmp_files_warn:
print('Without a directory for temporary files, smart cache progress \
will be reset when the program is shut down!\n\
To remove this warning, set the no_tmp_files_warn parameter to True')

def smart_cache(
self,
*,
start_TTL: time = time(minute=10),
max_TTL: time = time(hour=1),
min_TTL: time | None = time(minute=1)
) -> Callable:
def wrapper_func(target_func: Callable) -> Callable:
__cached_vals = {}


def cached_func_with_time(*args, **kwargs) -> Any:
cached_ = __cached_vals.get((*args, *kwargs), None)
if cached_ and cached_[0] > datetime.now():
return cached_[1]

result = target_func(*args, **kwargs)

__cached_vals[(*args, *kwargs)] = \
(datetime.now() + timedelta(hours=ttl.hour, minutes=ttl.minute, seconds=ttl.second), result)

return result


def cached_func_without_time(*args, **kwargs) -> Any:
try:
return __cached_vals[(*args, *kwargs)]
except KeyError:
result = target_func(*args, **kwargs)
__cached_vals[(*args, *kwargs)] = result
return result


return cached_func_with_time if ttl else cached_func_without_time
return wrapper_func


@AutoFreeze()
class CacheConfig:
funcs_ttl = {}
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
name = "frozenclass"
version = "0.1.1"
description = "Python module for convenient storage of classes in files."
authors = ["GigantPro <[email protected]>"]

authors = [
"GigantPro <[email protected]>"
]
maintainers = [
"GigantPro <[email protected]>"
]

license = "The GPLv3 License (GPLv3)"
readme = "README.rst"

Expand Down

0 comments on commit 0ff6277

Please sign in to comment.