lsst.pipe.base  15.0-6-gfa9b38f+10
struct.py
Go to the documentation of this file.
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 from __future__ import absolute_import, division
23 
24 from builtins import object
25 
26 __all__ = ["Struct"]
27 
28 
29 class Struct(object):
30  """A container to which you can add fields as attributes.
31 
32  Parameters
33  ----------
34  keyArgs
35  keyword arguments specifying fields and their values.
36 
37  Notes
38  -----
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.
41 
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.
46 
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.
50 
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).
54 
55  Examples
56  --------
57  >>> myStruct = Struct(
58  >>> strVal = 'the value of the field named "strVal"',
59  >>> intVal = 35,
60  >>> )
61 
62  """
63 
64  def __init__(self, **keyArgs):
65  object.__init__(self)
66  for name, val in keyArgs.items():
67  self.__safeAdd(name, val)
68 
69  def __safeAdd(self, name, val):
70  """Add a field if it does not already exist and name does not start with ``__`` (two underscores).
71 
72  Parameters
73  ----------
74  name : `str`
75  Name of field to add.
76  val : object
77  Value of field to add.
78 
79  Raises
80  ------
81  RuntimeError
82  Raised if name already exists or starts with ``__`` (two underscores).
83  """
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)
89 
90  def getDict(self):
91  """Get a dictionary of fields in this struct.
92 
93  Returns
94  -------
95  structDict : `dict`
96  Dictionary with field names as keys and field values as values. The values are shallow copies.
97  """
98  return self.__dict__.copy()
99 
100  def mergeItems(self, struct, *nameList):
101  """Copy specified fields from another struct, provided they don't already exist.
102 
103  Parameters
104  ----------
105  struct : `Struct`
106  `Struct` from which to copy.
107  *nameList : `str`
108  All remaining arguments are names of items to copy.
109 
110  Raises
111  ------
112  RuntimeError
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).
115 
116  Examples
117  --------
118  For example::
119 
120  foo.copyItems(other, "itemName1", "itemName2")
121 
122  copies ``other.itemName1`` and ``other.itemName2`` into self.
123  """
124  for name in nameList:
125  self.__safeAdd(name, getattr(struct, name))
126 
127  def copy(self):
128  """Make a one-level-deep copy (values are not copied).
129 
130  Returns
131  -------
132  copy : `Struct`
133  One-level-deep copy of this Struct.
134  """
135  return Struct(**self.getDict())
136 
137  def __eq__(self, other):
138  return self.__dict__ == other.__dict__
139 
140  def __len__(self):
141  return len(self.__dict__)
142 
143  def __repr__(self):
144  itemList = ["%s=%r" % (name, val) for name, val in self.getDict().items()]
145  return "%s(%s)" % (self.__class__.__name__, "; ".join(itemList))
def mergeItems(self, struct, nameList)
Definition: struct.py:100
def __eq__(self, other)
Definition: struct.py:137
def __init__(self, keyArgs)
Definition: struct.py:64
def __safeAdd(self, name, val)
Definition: struct.py:69