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

14 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-02-28 10:37 +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 

28from pydantic import BaseModel, Field 

29 

30 

31class DictConvertibleModel(BaseModel): 

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

33 representation is intentionally different from pydantics' own dict 

34 conversions. 

35 """ 

36 

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

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

39 """ 

40 

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

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

43 """ 

44 

45 @classmethod 

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

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

48 

49 Parameters 

50 ---------- 

51 content : `~collections.abc.Mapping` 

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

53 extra : `str`, optional 

54 Extra content that is not included in the dict representation 

55 

56 Returns 

57 ------- 

58 model : `DictConvertibleModel` 

59 New model. 

60 """ 

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

62 

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

64 """Convert the model to a dictionary. 

65 

66 Returns 

67 ------- 

68 content : `dict` 

69 Copy of ``self.content``. 

70 """ 

71 return self.content.copy()