27 """A container to which you can add fields as attributes.
32 keyword arguments specifying fields and their values.
36 Intended to be used for the return value from `~lsst.pipe.base.Task.run`
37 and other `~lsst.pipe.base.Task` methods, and useful for any method that
38 returns multiple values.
40 The intent is to allow accessing returned items by name, instead of
41 unpacking a tuple. This makes the code much more robust and easier to
42 read. It allows one to change what values are returned without inducing
43 mysterious failures: adding items is completely safe, and removing or
44 renaming items causes errors that are caught quickly and reported in a way
45 that is easy to understand.
47 The primary reason for using Struct instead of dict is that the fields may
48 be accessed as attributes, e.g. ``aStruct.foo`` instead of
49 ``aDict["foo"]``. Admittedly this only saves a few characters, but it
50 makes the code significantly more readable.
52 Struct is preferred over named tuples, because named tuples can be used as
53 ordinary tuples, thus losing all the safety advantages of Struct. In
54 addition, named tuples are clumsy to define and Structs are much more
55 mutable (e.g. one can trivially combine Structs and add additional fields).
59 >>> myStruct = Struct(
60 >>> strVal = 'the value of the field named "strVal"',
67 for name, val
in keyArgs.items():
70 def __safeAdd(self, name, val):
71 """Add a field if it does not already exist and name does not start
72 with ``__`` (two underscores).
79 Value of field to add.
84 Raised if name already exists or starts with ``__`` (two
87 if hasattr(self, name):
88 raise RuntimeError(f
"Item {name!r} already exists")
89 if name.startswith(
"__"):
90 raise RuntimeError(f
"Item name {name!r} invalid; must not begin with __")
91 setattr(self, name, val)
94 """Get a dictionary of fields in this struct.
99 Dictionary with field names as keys and field values as values.
100 The values are shallow copies.
105 """Copy specified fields from another struct, provided they don't
111 `Struct` from which to copy.
113 All remaining arguments are names of items to copy.
118 Raised if any item in nameList already exists in self (but any
119 items before the conflicting item in nameList will have been
126 foo.copyItems(other, "itemName1", "itemName2")
128 copies ``other.itemName1`` and ``other.itemName2`` into self.
130 for name
in nameList:
131 self.
__safeAdd__safeAdd(name, getattr(struct, name))
134 """Make a one-level-deep copy (values are not copied).
139 One-level-deep copy of this Struct.
144 return self.
__dict____dict__ == other.__dict__
150 itemsStr =
"; ".join(f
"{name}={val}" for name, val
in self.
getDictgetDict().items())
151 return f
"{self.__class__.__name__}({itemsStr})"
def __safeAdd(self, name, val)
def __init__(self, **keyArgs)
def mergeItems(self, struct, *nameList)