CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
iterators.py
Go to the documentation of this file.
1 # decorator for adding iterators to container like objects
2 # NOTE: EventBranch._readData has to be taken care of at another place!
3 
4 #import cmserror
5 
6 def addIterator(obj):
7  """function for adding iterators to objects"""
8  if not hasattr(obj, "__iter__"):
9  if hasattr(obj, "size"):
10  obj.__iter__ = iteratorForSizedObjects
11  else:
12  try:
13  begin, end = _findIterators(obj)
14  except:
15  return obj
16  if not hasattr(obj, "_begin") and hasattr(obj, "_end"):
17  obj._begin = begin
18  obj._end = end
19  obj.__iter__ = iteratorForBeginEnd
20  #else:
21  # obj.__iter__ = EmptyIterator
22  return obj
23 
24 
26  """dynamically added iterator"""
27  entries = container.size()
28  for entry in xrange(entries):
29  yield obj[entry]
30 
31 
33  """dynamically added iterator"""
34  it = self._begin
35  while (it != self.end):
36  yield begin.__deref__() #*b
37  begin.__preinc__() #++b
38 
39 
40 def emptyIterator(self):
41  """empty iterator"""
42  raise cmserror("Automatic iterator search failed for %s. Either it is no iterable or it has multiple iterator possibilites. Please use loop(begin, end) instead." %obj )
43 
44 
45 # automatic detection of iterators.
46 def _findIterators(obj):
47  objDict = obj.__dict__
48  _beginNames = [name for name in objDict.keys() if "begin" in
49 name.lower()]
50  _endNames = [name for name in objDict.keys() if "end" in name.lower()]
51  if len(_beginNames)==1 and len(_endNames)== 1 and _beginNames[0].lower().replace("begin","") == _endNames[0].lower().replace("end",""):
52  return objDict[_beginNames[0]], objDict[_endNames[0]]
53  else:
54  return False
55 
56 
57 
58 ##########################
59 if __name__ == "__main__":
60 
61  import unittest
62  class TestIterators(unittest.TestCase):
63 
64  def testFindIterators(self):
65  class A(object):
66  pass
67  a = A()
68  a.BeGin_foo = 1
69  a.EnD_foo = 100
70  self.assertEqual(_findIterators(a),(1,100))
71  a.begin_bar = 1
72  a.end_bar = 100
73  self.failIf(_findIterators(a))
74 
75  def testAddIterator(self):
76  # test for size types
77  class A(object):
78  size = 3
79  a = A()
80  a = addIterator(a)
81  self.assert_(hasattr(a, "__iter__"))
82  # test if __iter__ already there
83  class B(object):
84  def __iter__(self):
85  return True
86  b = B()
87  b = addIterator(b)
88  self.assert_(b.__iter__())
89 
90 
91  unittest.main()
92 
93 
def iteratorForSizedObjects
Definition: iterators.py:25
def iteratorForBeginEnd
Definition: iterators.py:32
list object
Definition: dbtoconf.py:77