Skip to content

Commit

Permalink
Add deep copy function
Browse files Browse the repository at this point in the history
Leaving the alpha version
  • Loading branch information
GigantPro committed Apr 6, 2023
1 parent 321b185 commit c878463
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 15 deletions.
4 changes: 2 additions & 2 deletions frozenclass/data_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def get_all_saves(self) -> list[Any]:
classes_list = []

for save in list_dir:
classes_list.append(DataParser(f"{self._saves_path}/{save}").parse_file())
classes_list.append(DataParser(f"{self._saves_path}/{save}", self).parse_file())

return classes_list

Expand Down Expand Up @@ -85,7 +85,7 @@ def load_save(self, save_name: str) -> Any:
list_dir = os.listdir(self._saves_path)

for save_filename in list_dir:
parser = DataParser(f"{self._saves_path}/{save_filename}")
parser = DataParser(f"{self._saves_path}/{save_filename}", self)
parsed_content = parser.parse_file_content()
if parsed_content["SavedModel"]["save_name"] == save_name:
return parser.parse_file()
Expand Down
19 changes: 17 additions & 2 deletions frozenclass/dataparser/data_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@


class DataParser:
def __init__(self, filename: str) -> None:
def __init__(self, filename: str, data_controller_obj) -> None:
self.filename = filename
self.data_controller_obj = data_controller_obj

self.saved_data = {}
self._class = None

def parse_file(self) -> Any:
self.saved_data = self.parse_file_content()
self._encoding_dict_keys()
self.saved_data = self._encoding_deep_keys(self.saved_data)

self._class = types.get_type_by_saved_type(self.saved_data["type"]["class_path"])

Expand Down Expand Up @@ -101,5 +103,18 @@ def __parse_value_name(self, key: str) -> str:

if spec_type == 'type':
new_key = \
TypesModule().get_value_by_type(key_value, spec_value)
types.get_value_by_type(key_value, spec_value)
return new_key

def _encoding_deep_keys(self, data: dict) -> dict:
new_var_desc = []
for var_desc in data['var']:
if '@frozenclass|' in var_desc['var_value']:
var_desc['var_value'] = var_desc['var_value'][13:]
name_, value_ = var_desc['var_value'].split('?')

if name_ == 'saved_data':
var_desc['var_value'] = self.data_controller_obj.load_save(value_)
new_var_desc.append(var_desc)
data['var'] = new_var_desc
return data
10 changes: 2 additions & 8 deletions frozenclass/dataparser/data_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,6 @@ def deep_freeze(self, class_: Callable) -> str:
self._check_save_name()
self.class_ = class_

# self.parsed_attributes = self._deep_parse_attributes(self.class_)
# self._vars_filter()
# self._remake_dict_keys()

self._save_deep_data(self.class_)
return self.save_name

Expand Down Expand Up @@ -214,7 +210,7 @@ def __save_by_data(self, data: dict, recursion_num: int = 0) -> None:
if data[attrname]['var_type_import'] not in STANDART_TYPES:
self.__save_by_data(data[attrname], recursion_num + 1)
new_attrs = data[attrname]
new_attrs['var_value'] = f'@frozenclass|saved_data={self.save_name}:{recursion_num + 1}'
new_attrs['var_value'] = f'@frozenclass|saved_data?{self.save_name}:{recursion_num + 1}'
res += VAR_TEMPLATE.format(**new_attrs)
elif data[attrname]['var_type'] in JSON_FORMATS:
new_attr = deepcopy(data[attrname])
Expand All @@ -232,15 +228,13 @@ def __save_by_data(self, data: dict, recursion_num: int = 0) -> None:
class_parents=TypesModule().get_json_bases_data_by_class(TypesModule()\
.get_type_by_saved_type(data["var_type_import"])),
)
print(data)

for attrname in data['var_value']:
res += "\n"
print(attrname)
if data['var_value'][attrname]['var_type_import'] not in STANDART_TYPES:
self.__save_by_data(data['var_value'][attrname], recursion_num + 1)
new_attrs = data['var_value'][attrname]
new_attrs['var_value'] = f'@frozenclass|saved_data={self.save_name}:{recursion_num + 1}'
new_attrs['var_value'] = f'@frozenclass|saved_data?{self.save_name}:{recursion_num + 1}'
res += VAR_TEMPLATE.format(**new_attrs)
elif data['var_value'][attrname]['var_type'] in JSON_FORMATS:
new_attr = deepcopy(data['var_value'][attrname])
Expand Down
11 changes: 10 additions & 1 deletion frozenclass/dataparser/types_modul.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,16 @@ def _get_var_with_type(var_description: dict) -> tuple[str, Any]:
res_class = class_()

for var in vars:
setattr(res_class, *_get_var_with_type(var))
var_type_now = self.get_type_by_saved_type(var['class_path'])

if var_type_now is None and var['class_path'] != 'NoneType' and not isinstance(var['var_value'], str):
setattr(res_class, var['var_name'], var['var_value'])

elif isinstance(var['var_value'], var_type_now):
setattr(res_class, var['var_name'], var['var_value'])

else:
setattr(res_class, *_get_var_with_type(var))

return res_class

Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "frozenclass"
version = "0.0.7a1"
version = "0.0.8"
description = "Python module for convenient storage of classes in files."
authors = ["GigantPro <[email protected]>"]
license = "The GPLv3 License (GPLv3)"
Expand All @@ -24,7 +24,7 @@ build = "scripts.build:build"
public = "scripts.public:public"
linting = "scripts.pylint:start_linting"
testing = "scripts.testing:start_testing"
autoclean = "scripts.autoclean:autoclean"
clean = "scripts.autoclean:autoclean"

[tool.pylint]
max-line-length = 120
Expand Down
47 changes: 47 additions & 0 deletions tests/test_deep_save_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from random import choice
from string import ascii_letters
import pytest

from frozenclass import DataController


class PublicClassA:
third = '123'


class PublicClassB:
first = 123
second = PublicClassA()


def test_save_load_deep_with_globals_bases():
ts_object = PublicClassB()

controller = DataController("test_saves")

save_name = controller.deep_freeze(ts_object)

new_class = controller.load_save(save_name)

assert new_class.first == 123 and new_class.second.third == '123'


def test_save_load_deep_with_locals_bases():
class LocalClassA:
third = '123'


class LocalClassB:
first = 123
second = LocalClassA()


ts_object = LocalClassB()

controller = DataController("test_saves")

save_name = controller.deep_freeze(ts_object)

new_class = controller.load_save(save_name)

assert new_class.first == 123 and new_class.second.third == '123'

0 comments on commit c878463

Please sign in to comment.