lsst.pipe.base  13.0-11-gdf6a56c+13
 All Classes Namespaces Files Functions Variables Pages
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 struct to which you can add any fields
31 
32  Intended to be used for the return value from Task.run and other Task methods,
33  and useful for any method that returns multiple values.
34 
35  The intent is to allow accessing returned items by name, instead of unpacking a tuple.
36  This makes the code much more robust and easier to read. It allows one to change what values are returned
37  without inducing mysterious failures: adding items is completely safe, and removing or renaming items
38  causes errors that are caught quickly and reported in a way that is easy to understand.
39 
40  The primary reason for using Struct instead of dict is that the fields may be accessed as attributes,
41  e.g. aStruct.foo instead of aDict["foo"]. Admittedly this only saves a few characters, but it makes
42  the code significantly more readable.
43 
44  Struct is preferred over named tuples, because named tuples can be used as ordinary tuples, thus losing
45  all the safety advantages of Struct. In addition, named tuples are clumsy to define and Structs
46  are much more mutable (e.g. one can trivially combine Structs and add additional fields).
47  """
48 
49  def __init__(self, **keyArgs):
50  """!Create a Struct with the specified field names and values
51 
52  For example:
53  @code
54  myStruct = Struct(
55  strVal = 'the value of the field named "strVal"',
56  intVal = 35,
57  )
58  @endcode
59 
60  @param[in] **keyArgs keyword arguments specifying name=value pairs
61  """
62  object.__init__(self)
63  for name, val in keyArgs.items():
64  self.__safeAdd(name, val)
65 
66  def __safeAdd(self, name, val):
67  """!Add a field if it does not already exist and name does not start with __ (two underscores)
68 
69  @param[in] name name of field to add
70  @param[in] val value of field to add
71 
72  @throw RuntimeError if name already exists or starts with __ (two underscores)
73  """
74  if hasattr(self, name):
75  raise RuntimeError("Item %s already exists" % (name,))
76  if name.startswith("__"):
77  raise RuntimeError("Item name %r invalid; must not begin with __" % (name,))
78  setattr(self, name, val)
79 
80  def getDict(self):
81  """!Return a dictionary of attribute name: value
82 
83  @warning: the values are shallow copies.
84  """
85  return self.__dict__.copy()
86 
87  def mergeItems(self, struct, *nameList):
88  """!Copy specified fields from another struct, provided they don't already exist
89 
90  @param[in] struct struct from which to copy
91  @param[in] *nameList all remaining arguments are names of items to copy
92 
93  For example: foo.copyItems(other, "itemName1", "itemName2")
94  copies other.itemName1 and other.itemName2 into self.
95 
96  @throw RuntimeError if any item in nameList already exists in self
97  (but any items before the conflicting item in nameList will have been copied)
98  """
99  for name in nameList:
100  self.__safeAdd(name, getattr(struct, name))
101 
102  def copy(self):
103  """!Return a one-level-deep copy (values are not copied)
104  """
105  return Struct(**self.getDict())
106 
107  def __eq__(self, other):
108  return self.__dict__ == other.__dict__
109 
110  def __len__(self):
111  return len(self.__dict__)
112 
113  def __repr__(self):
114  itemList = ["%s=%r" % (name, val) for name, val in self.getDict().items()]
115  return "%s(%s)" % (self.__class__.__name__, "; ".join(itemList))
def __init__
Create a Struct with the specified field names and values.
Definition: struct.py:49
def copy
Return a one-level-deep copy (values are not copied)
Definition: struct.py:102
A struct to which you can add any fields.
Definition: struct.py:29
def __safeAdd
Add a field if it does not already exist and name does not start with __ (two underscores) ...
Definition: struct.py:66
def getDict
Return a dictionary of attribute name: value.
Definition: struct.py:80
def mergeItems
Copy specified fields from another struct, provided they don&#39;t already exist.
Definition: struct.py:87