Coverage for mongodb_odm / data_conversion.py: 100%

36 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-12-07 08:37 +0000

1from collections.abc import Generator 1abcdef

2from typing import Any, Union 1abcdef

3 

4 

5class ODMObj: 1abcdef

6 """ 

7 We will convert the pymongo dict to this class 

8 so that the user can use the '.' operation. 

9 """ 

10 

11 def __repr__(self) -> str: 1abcdef

12 items = (f"{k}={self.__dict__[k]}" for k in self.__dict__) 1abcdef

13 return "{}({})".format(type(self).__name__, ", ".join(items)) 1abcdef

14 

15 def __str__(self) -> str: 1abcdef

16 return self.__repr__() 1abcdef

17 

18 def __eq__(self, other: object) -> bool: 1abcdef

19 return self.__dict__ == other.__dict__ 1abcdef

20 

21 def __iter__(self) -> Generator[tuple[str, Any], None, None]: 1abcdef

22 yield from self.__dict__.items() 1abcdef

23 

24 def dict(self) -> Any: 1abcdef

25 return _to_dict(self) 1abcdef

26 

27 

28def _to_dict(obj: Any) -> Any: 1abcdef

29 # This function will convert the ODMObj obj to dict again 

30 if isinstance(obj, list): 1abcdef

31 obj = [_to_dict(x) for x in obj] 1abcdef

32 if not isinstance(obj, ODMObj): 1abcdef

33 return obj 1abcdef

34 

35 n_d = {} 1abcdef

36 for k, v in obj: 1abcdef

37 n_d[k] = _to_dict(v) 1abcdef

38 return n_d 1abcdef

39 

40 

41def _to_obj(d: Union[dict[str, Any], list[Any]]) -> Any: 1abcdef

42 if isinstance(d, list): 1abcdef

43 d = [_to_obj(x) for x in d] 1abcdef

44 if not isinstance(d, dict): 1abcdef

45 return d 1abcdef

46 

47 obj = ODMObj() 1abcdef

48 for k, v in d.items(): 1abcdef

49 obj.__dict__[k] = _to_obj(v) 1abcdef

50 if k == "_id": 1abcdef

51 obj.__dict__["id"] = obj.__dict__[k] 1abcdef

52 return obj 1abcdef

53 

54 

55def dict2obj(d: dict[str, Any]) -> Any: 1abcdef

56 return _to_obj(d) 1abcdef