Coverage for python/lsst/daf/butler/tests/dict_convertible_model.py: 89%

17 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-14 19:21 +0000

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <http://www.gnu.org/licenses/>. 

21 

22from __future__ import annotations 

23 

24__all__ = () 

25 

26from collections.abc import Mapping 

27 

28try: 

29 from pydantic.v1 import BaseModel, Field 

30except ModuleNotFoundError: 

31 from pydantic import BaseModel, Field # type: ignore 

32 

33 

34class DictConvertibleModel(BaseModel): 

35 """A pydantic model to/from dict conversion in which the dict 

36 representation is intentionally different from pydantics' own dict 

37 conversions. 

38 """ 

39 

40 content: dict[str, str] = Field(default_factory=dict) 

41 """Content of the logical dict that this object converts to (`dict`). 

42 """ 

43 

44 extra: str = Field(default="") 

45 """Extra content that is not included in the dict representation (`str`). 

46 """ 

47 

48 @classmethod 

49 def from_dict(cls, content: Mapping[str, str], extra: str = "from_dict") -> DictConvertibleModel: 

50 """Construct an instance from a `dict`. 

51 

52 Parameters 

53 ---------- 

54 content : `~collections.abc.Mapping` 

55 Content of the logical dict that this object converts to. 

56 extra : `str`, optional 

57 Extra content that is not included in the dict representation 

58 

59 Returns 

60 ------- 

61 model : `DictConvertibleModel` 

62 New model. 

63 """ 

64 return cls(content=dict(content), extra=extra) 

65 

66 def to_dict(self) -> dict[str, str]: 

67 """Convert the model to a dictionary. 

68 

69 Returns 

70 ------- 

71 content : `dict` 

72 Copy of ``self.content``. 

73 """ 

74 return self.content.copy()