Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into AddSmartCache
Browse files Browse the repository at this point in the history
  • Loading branch information
GigantPro committed Aug 30, 2023
2 parents 0ff6277 + 782b42f commit a38dcde
Show file tree
Hide file tree
Showing 18 changed files with 144 additions and 81 deletions.
13 changes: 10 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ jobs:
matrix:
os:
- ubuntu-latest
- windows-latest
- macos-latest
python-version:
- '3.7'
- '3.8'
Expand All @@ -21,17 +19,26 @@ jobs:
- '3.11'
runs-on: ${{ matrix.os }}
steps:

- name: Checkout repository
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Pip upgrade
run: python -m pip install --upgrade pip

- name: Poetry install
run: pip install poetry

- name: Install dependencies
run: python -m poetry install --with dev

- name: Build
run: python -m poetry run python setup.py develop

- name: Run tests
run: python -m poetry run testing
run: cd tests && python -m poetry run python -m pytest
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ frozenclass.egg-info
.pytest_cache
test_saves
docs/_build
venv
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"autoDocstring.docstringFormat": "sphinx",
"esbonio.sphinx.confDir": ""
"esbonio.sphinx.confDir": "",
"nuxt.isNuxtApp": false
}
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
along with this program. If not, see <http://www.gnu.org/licenses/>.
5 changes: 3 additions & 2 deletions frozenclass/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from .dataparser import DataParser
from .dataparser import DataWriter
from . import exceptions, dataparser, functions

from .dataparser import DataParser, DataWriter

from .data_controller import DataController
from .auto_freeze import AutoFreeze
Expand Down
2 changes: 1 addition & 1 deletion frozenclass/auto_freeze.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __custom_init(self, *args, **kwargs) -> None:
except NoSave:
self.__freeze_class()
else:
print(saved_vars)
# print(saved_vars)
for saved_var in saved_vars:
self.__setattr__(saved_var, saved_vars[saved_var])

Expand Down
35 changes: 31 additions & 4 deletions frozenclass/cache.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Any, Callable
from typing import Any, Callable, Optional
from datetime import time, datetime, timedelta

from .auto_freeze import AutoFreeze
Expand All @@ -9,19 +9,21 @@

class CacheController:
"""The main class of the cache logic. Includes all caches logic"""
def cache(*, ttl: time | None = time(minute=10)) -> Callable: # ( TTL_end, result )
def cache(*, ttl: Optional[time] = time(minute=10),
is_async: bool = False) -> Callable: # ( TTL_end, result )
"""Function-decorate for runtime caching.
The cache can either be overwritten or remain until the program terminates.
:param ttl: Time-To-Live of cached valume, defaults to time(minute=10)
:type ttl: time | None, optional
:param is_async: Set True if decorated func is async, defaults to False
:type is_async: bool, optional
:return: Decorated func
:rtype: 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():
Expand All @@ -44,7 +46,32 @@ def cached_func_without_time(*args, **kwargs) -> Any:
return result


return cached_func_with_time if ttl else cached_func_without_time
async def async_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 = await target_func(*args, **kwargs)

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

return result


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


if not is_async:
return cached_func_with_time if ttl else cached_func_without_time
return async_cached_func_with_time if ttl else async_cached_func_without_time

return wrapper_func

def __init__(self, path_to_temp_files: Path | None, *, no_tmp_files_warn: bool = False) -> None:
Expand Down
4 changes: 2 additions & 2 deletions frozenclass/data_controller.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any
from typing import Any, List
import os
from shutil import copyfile
import platform
Expand All @@ -20,7 +20,7 @@ def __init__(self, saves_folder_path: str) -> None:

os.makedirs(self._saves_path, exist_ok=True)

def get_all_saves(self) -> list[Any]:
def get_all_saves(self) -> List[Any]:
"""Will return you instances of all previously saved classes.
Returns:
Expand Down
2 changes: 2 additions & 0 deletions frozenclass/dataparser/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
__all__ = ("DataParser", "DataWriter")

from .data_parser import DataParser
from .data_writer import DataWriter
8 changes: 4 additions & 4 deletions frozenclass/dataparser/data_parser.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any
from typing import Any, Optional, Union, Dict
import json
from copy import deepcopy

Expand Down Expand Up @@ -32,13 +32,13 @@ def parse_file(self) -> Any:
type_ = generate_class_by_info(self.saved_data)
return create_class_instance(type_, self.saved_data["var"])

def parse_saved_args(self) -> dict[str: Any]:
def parse_saved_args(self) -> Dict[str, Any]:
self.saved_data = self.parse_file_content()
self._encoding_dict_keys()
self.saved_data = self._encoding_deep_keys(self.saved_data)
return self._get_vars_from_saved_data(self.saved_data)

def _get_vars_from_saved_data(self, saved_data: dict) -> dict[str: Any]:
def _get_vars_from_saved_data(self, saved_data: dict) -> Dict[str, Any]:
if saved_data['var'] is None:
return {}

Expand All @@ -47,7 +47,7 @@ def _get_vars_from_saved_data(self, saved_data: dict) -> dict[str: Any]:
res[var_desc['var_name']] = get_value_by_type(var_desc['var_value'], var_desc['var_type'])
return res

def parse_file_content(self, file_name: str | None = None) -> dict[Any] | None:
def parse_file_content(self, file_name: Optional[str] = None) -> Union[Dict, None]:
file_name = file_name if file_name else self.filename
with open(file_name, "r", encoding="utf-8") as file:
try:
Expand Down
6 changes: 3 additions & 3 deletions frozenclass/dataparser/data_writer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from copy import deepcopy
import json
from typing import Any, Callable
from typing import Any, Callable, Optional, Tuple
from random import randint
from datetime import datetime

Expand All @@ -16,7 +16,7 @@


class DataWriter:
def __init__(self, saves_path: str, save_name: str | None = None) -> None:
def __init__(self, saves_path: str, save_name: Optional[str] = None) -> None:
self.save_name = save_name
self.saves_path = saves_path

Expand Down Expand Up @@ -64,7 +64,7 @@ def _parse_attributes(self) -> dict:
}
return res

def _parse_type_by_target(self, target_: Any) -> tuple[str, str]:
def _parse_type_by_target(self, target_: Any) -> Tuple[str]:
str_type = str(type(target_))
return str_type.split("'")[-2].split(".")[-1], str_type.split("'")[-2]

Expand Down
10 changes: 5 additions & 5 deletions frozenclass/dataparser/types_module.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import inspect
import json
from typing import Any, Callable
from typing import Any, Callable, Union, Dict, Tuple

from ..exceptions import NoVar
from .const import STANDART_TYPES
Expand All @@ -15,7 +15,7 @@ def get_value_by_type(value: Any, type_: str) -> Any:
return class_obj(value)
return value

def get_type_by_saved_type(type_data: str) -> Any | None:
def get_type_by_saved_type(type_data: str) -> Union[Any, None]:
components = type_data.split(".")
if components[0] in STANDART_TYPES:
return STANDART_TYPES[components[0]]
Expand All @@ -29,9 +29,9 @@ def get_type_by_saved_type(type_data: str) -> Any | None:
return mod

def create_class_instance(
class_: Callable, vars: dict[str:Any]
class_: Callable, vars: Dict[str, Any]
) -> Any:
def _get_var_with_type(var_description: dict) -> tuple[str, Any]:
def _get_var_with_type(var_description: dict) -> Tuple[str, Any]:
type_ = get_type_by_saved_type(var_description["class_path"])
value = type_(var_description["var_value"])

Expand Down Expand Up @@ -89,7 +89,7 @@ def get_json_bases_data_by_class(class_: Callable) -> str:
bases_list = s_bases.split('\'')[1::2]
return json.dumps(bases_list)

def get_parents_by_json(json_: list) -> tuple[Callable]:
def get_parents_by_json(json_: list) -> Tuple[Callable]:
parents_list_str = json.loads(json_['type']['class_parents'])
parents_list = [get_type_by_saved_type(parent) for parent in parents_list_str]
for i in range(len(parents_list)):
Expand Down
2 changes: 2 additions & 0 deletions frozenclass/exceptions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
__all__ = ("NoVar", "NoSave")

from .no_var import NoVar
from .no_save import NoSave
2 changes: 2 additions & 0 deletions frozenclass/functions/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
__all__ = ("parse_name",)

from .parse_name import parse_name
Loading

0 comments on commit a38dcde

Please sign in to comment.