Coverage for python/lsst/pipe/base/struct.py: 34%
28 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-04-12 09:13 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2023-04-12 09:13 +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#
23from __future__ import annotations
25__all__ = ["Struct"]
27from types import SimpleNamespace
28from typing import Any, Dict
31class Struct(SimpleNamespace):
32 """A container to which you can add fields as attributes.
34 Parameters
35 ----------
36 keyArgs
37 keyword arguments specifying fields and their values.
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.
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.
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.
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).
62 Examples
63 --------
64 >>> myStruct = Struct(
65 >>> strVal = 'the value of the field named "strVal"',
66 >>> intVal = 35,
67 >>> )
69 """
71 def __init__(self, **keyArgs: Any):
72 for name, val in keyArgs.items():
73 self.__safeAdd(name, val)
75 def __safeAdd(self, name: str, val: Any) -> None:
76 """Add a field if it does not already exist and name does not start
77 with ``__`` (two underscores).
79 Parameters
80 ----------
81 name : `str`
82 Name of field to add.
83 val : object
84 Value of field to add.
86 Raises
87 ------
88 RuntimeError
89 Raised if name already exists or starts with ``__`` (two
90 underscores).
91 """
92 if hasattr(self, name):
93 raise RuntimeError(f"Item {name!r} already exists")
94 if name.startswith("__"):
95 raise RuntimeError(f"Item name {name!r} invalid; must not begin with __")
96 setattr(self, name, val)
98 def getDict(self) -> Dict[str, Any]:
99 """Get a dictionary of fields in this struct.
101 Returns
102 -------
103 structDict : `dict`
104 Dictionary with field names as keys and field values as values.
105 The values are shallow copies.
106 """
107 return self.__dict__.copy()
109 def mergeItems(self, struct: Struct, *nameList: str) -> None:
110 """Copy specified fields from another struct, provided they don't
111 already exist.
113 Parameters
114 ----------
115 struct : `Struct`
116 `Struct` from which to copy.
117 *nameList : `str`
118 All remaining arguments are names of items to copy.
120 Raises
121 ------
122 RuntimeError
123 Raised if any item in nameList already exists in self (but any
124 items before the conflicting item in nameList will have been
125 copied).
127 Examples
128 --------
129 For example::
131 foo.copyItems(other, "itemName1", "itemName2")
133 copies ``other.itemName1`` and ``other.itemName2`` into self.
134 """
135 for name in nameList:
136 self.__safeAdd(name, getattr(struct, name))
138 def copy(self) -> Struct:
139 """Make a one-level-deep copy (values are not copied).
141 Returns
142 -------
143 copy : `Struct`
144 One-level-deep copy of this Struct.
145 """
146 return Struct(**self.getDict())
148 def __eq__(self, other: Any) -> bool:
149 return self.__dict__ == other.__dict__
151 def __len__(self) -> int:
152 return len(self.__dict__)
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})"