22 from __future__
import absolute_import, division
24 from builtins
import object
30 """A container to which you can add fields as attributes.
35 keyword arguments specifying fields and their values.
39 Intended to be used for the return value from `~lsst.pipe.base.Task.run` and other `~lsst.pipe.base.Task`
40 methods, and useful for any method that returns multiple values.
42 The intent is to allow accessing returned items by name, instead of unpacking a tuple.
43 This makes the code much more robust and easier to read. It allows one to change what values are returned
44 without inducing mysterious failures: adding items is completely safe, and removing or renaming items
45 causes errors that are caught quickly and reported in a way that is easy to understand.
47 The primary reason for using Struct instead of dict is that the fields may be accessed as attributes,
48 e.g. ``aStruct.foo`` instead of ``aDict["foo"]``. Admittedly this only saves a few characters, but it
49 makes the code significantly more readable.
51 Struct is preferred over named tuples, because named tuples can be used as ordinary tuples, thus losing
52 all the safety advantages of Struct. In addition, named tuples are clumsy to define and Structs
53 are much more mutable (e.g. one can trivially combine Structs and add additional fields).
57 >>> myStruct = Struct(
58 >>> strVal = 'the value of the field named "strVal"',
66 for name, val
in keyArgs.items():
69 def __safeAdd(self, name, val):
70 """Add a field if it does not already exist and name does not start with ``__`` (two underscores).
77 Value of field to add.
82 Raised if name already exists or starts with ``__`` (two underscores).
84 if hasattr(self, name):
85 raise RuntimeError(
"Item %s already exists" % (name,))
86 if name.startswith(
"__"):
87 raise RuntimeError(
"Item name %r invalid; must not begin with __" % (name,))
88 setattr(self, name, val)
91 """Get a dictionary of fields in this struct.
96 Dictionary with field names as keys and field values as values. The values are shallow copies.
98 return self.__dict__.copy()
101 """Copy specified fields from another struct, provided they don't already exist.
106 `Struct` from which to copy.
108 All remaining arguments are names of items to copy.
113 Raised if any item in nameList already exists in self (but any items before the conflicting item
114 in nameList will have been copied).
120 foo.copyItems(other, "itemName1", "itemName2")
122 copies ``other.itemName1`` and ``other.itemName2`` into self.
124 for name
in nameList:
125 self.
__safeAdd(name, getattr(struct, name))
128 """Make a one-level-deep copy (values are not copied).
133 One-level-deep copy of this Struct.
138 return self.
__dict__ == other.__dict__
144 itemList = [
"%s=%r" % (name, val)
for name, val
in self.
getDict().items()]
145 return "%s(%s)" % (self.__class__.__name__,
"; ".join(itemList))