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

26 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-18 08:44 +0000

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 types import SimpleNamespace 

28from typing import Any 

29 

30 

31class Struct(SimpleNamespace): 

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

33 

34 Parameters 

35 ---------- 

36 **keyArgs 

37 Keyword arguments specifying fields and their values. 

38 

39 Notes 

40 ----- 

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

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

43 returns multiple values. 

44 

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

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

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

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

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

50 that is easy to understand. 

51 

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

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

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

55 makes the code significantly more readable. 

56 

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

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

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

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

61 

62 Examples 

63 -------- 

64 >>> myStruct = Struct( 

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

66 >>> intVal = 35, 

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 Returns 

120 ------- 

121 None 

122 

123 Raises 

124 ------ 

125 RuntimeError 

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

127 items before the conflicting item in nameList will have been 

128 copied). 

129 

130 Examples 

131 -------- 

132 For example:: 

133 

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

135 

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

137 """ 

138 for name in nameList: 

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

140 

141 def copy(self) -> Struct: 

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

143 

144 Returns 

145 ------- 

146 copy : `Struct` 

147 One-level-deep copy of this Struct. 

148 """ 

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

150 

151 def __len__(self) -> int: 

152 return len(self.__dict__) 

153 

154 def __repr__(self) -> str: 

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

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