Coverage for python/lsst/pipe/base/struct.py: 32%

27 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-01-06 01:57 -0800

1# 

2# LSST Data Management System 

3# Copyright 2008, 2009, 2010, 2011 LSST Corporation. 

4# 

5# This product includes software developed by the 

6# LSST Project (http://www.lsst.org/). 

7# 

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

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

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

11# (at your option) any later version. 

12# 

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

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

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

16# GNU General Public License for more details. 

17# 

18# You should have received a copy of the LSST License Statement and 

19# the GNU General Public License along with this program. If not, 

20# see <http://www.lsstcorp.org/LegalNotices/>. 

21# 

22 

23from __future__ import annotations 

24 

25__all__ = ["Struct"] 

26 

27from typing import Any, Dict 

28 

29 

30class Struct: 

31 """A container to which you can add fields as attributes. 

32 

33 Parameters 

34 ---------- 

35 keyArgs 

36 keyword arguments specifying fields and their values. 

37 

38 Notes 

39 ----- 

40 Intended to be used for the return value from `~lsst.pipe.base.Task.run` 

41 and other `~lsst.pipe.base.Task` methods, and useful for any method that 

42 returns multiple values. 

43 

44 The intent is to allow accessing returned items by name, instead of 

45 unpacking a tuple. This makes the code much more robust and easier to 

46 read. It allows one to change what values are returned without inducing 

47 mysterious failures: adding items is completely safe, and removing or 

48 renaming items causes errors that are caught quickly and reported in a way 

49 that is easy to understand. 

50 

51 The primary reason for using Struct instead of dict is that the fields may 

52 be accessed as attributes, e.g. ``aStruct.foo`` instead of 

53 ``aDict["foo"]``. Admittedly this only saves a few characters, but it 

54 makes the code significantly more readable. 

55 

56 Struct is preferred over named tuples, because named tuples can be used as 

57 ordinary tuples, thus losing all the safety advantages of Struct. In 

58 addition, named tuples are clumsy to define and Structs are much more 

59 mutable (e.g. one can trivially combine Structs and add additional fields). 

60 

61 Examples 

62 -------- 

63 >>> myStruct = Struct( 

64 >>> strVal = 'the value of the field named "strVal"', 

65 >>> intVal = 35, 

66 >>> ) 

67 

68 """ 

69 

70 def __init__(self, **keyArgs: Any): 

71 for name, val in keyArgs.items(): 

72 self.__safeAdd(name, val) 

73 

74 def __safeAdd(self, name: str, val: Any) -> None: 

75 """Add a field if it does not already exist and name does not start 

76 with ``__`` (two underscores). 

77 

78 Parameters 

79 ---------- 

80 name : `str` 

81 Name of field to add. 

82 val : object 

83 Value of field to add. 

84 

85 Raises 

86 ------ 

87 RuntimeError 

88 Raised if name already exists or starts with ``__`` (two 

89 underscores). 

90 """ 

91 if hasattr(self, name): 

92 raise RuntimeError(f"Item {name!r} already exists") 

93 if name.startswith("__"): 

94 raise RuntimeError(f"Item name {name!r} invalid; must not begin with __") 

95 setattr(self, name, val) 

96 

97 def getDict(self) -> Dict[str, Any]: 

98 """Get a dictionary of fields in this struct. 

99 

100 Returns 

101 ------- 

102 structDict : `dict` 

103 Dictionary with field names as keys and field values as values. 

104 The values are shallow copies. 

105 """ 

106 return self.__dict__.copy() 

107 

108 def mergeItems(self, struct: Struct, *nameList: str) -> None: 

109 """Copy specified fields from another struct, provided they don't 

110 already exist. 

111 

112 Parameters 

113 ---------- 

114 struct : `Struct` 

115 `Struct` from which to copy. 

116 *nameList : `str` 

117 All remaining arguments are names of items to copy. 

118 

119 Raises 

120 ------ 

121 RuntimeError 

122 Raised if any item in nameList already exists in self (but any 

123 items before the conflicting item in nameList will have been 

124 copied). 

125 

126 Examples 

127 -------- 

128 For example:: 

129 

130 foo.copyItems(other, "itemName1", "itemName2") 

131 

132 copies ``other.itemName1`` and ``other.itemName2`` into self. 

133 """ 

134 for name in nameList: 

135 self.__safeAdd(name, getattr(struct, name)) 

136 

137 def copy(self) -> Struct: 

138 """Make a one-level-deep copy (values are not copied). 

139 

140 Returns 

141 ------- 

142 copy : `Struct` 

143 One-level-deep copy of this Struct. 

144 """ 

145 return Struct(**self.getDict()) 

146 

147 def __eq__(self, other: Any) -> bool: 

148 return self.__dict__ == other.__dict__ 

149 

150 def __len__(self) -> int: 

151 return len(self.__dict__) 

152 

153 def __repr__(self) -> str: 

154 itemsStr = "; ".join(f"{name}={val}" for name, val in self.getDict().items()) 

155 return f"{self.__class__.__name__}({itemsStr})"