Skip to content

Commit f11f3ce

Browse files
committed
added helper function to convert spockspaces to dict that is outside of the SpockBulder object -- lol forgoat to add file
1 parent a8d9f89 commit f11f3ce

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

spock/helpers.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
3+
# SPDX-License-Identifier: Apache-2.0
4+
5+
"""Helper functions for Spock"""
6+
7+
from typing import Dict, List, Optional, Tuple, Union
8+
9+
from spock.backend.saver import AttrSaver
10+
from spock.backend.wrappers import Spockspace
11+
from spock.exceptions import _SpockValueError
12+
from spock.utils import _C, _is_spock_instance
13+
14+
15+
def to_dict(
16+
objs: Union[_C, List[_C], Tuple[_C, ...]], saver: Optional[AttrSaver] = AttrSaver()
17+
) -> Dict[str, Dict]:
18+
"""Converts spock classes from a Spockspace into their dictionary representations
19+
20+
Args:
21+
objs: single spock class or an iterable of spock classes
22+
saver: optional saver class object
23+
24+
Returns:
25+
dictionary where the class names are keys and the values are the dictionary
26+
representations
27+
"""
28+
if isinstance(objs, (List, Tuple)):
29+
obj_dict = {}
30+
for val in objs:
31+
if not _is_spock_instance(val):
32+
raise _SpockValueError(
33+
f"Object is not a @spock decorated class object -- "
34+
f"currently `{type(val)}`"
35+
)
36+
obj_dict.update({type(val).__name__: val})
37+
elif _is_spock_instance(objs):
38+
obj_dict = {type(objs).__name__: objs}
39+
else:
40+
raise _SpockValueError(
41+
f"Object is not a @spock decorated class object -- "
42+
f"currently `{type(objs)}`"
43+
)
44+
return saver.dict_payload(Spockspace(**obj_dict))

0 commit comments

Comments
 (0)