Package Ganga :: Package Utility :: Module util
[hide private]
[frames] | no frames]

Source Code for Module Ganga.Utility.util

  1  ################################################################################ 
  2  # Ganga Project. http://cern.ch/ganga 
  3  # 
  4  # $Id: util.py,v 1.1 2008-07-17 16:41:01 moscicki Exp $ 
  5  ################################################################################ 
  6   
  7  """ 
  8   This file contains general-purpose utilities, mainly Python Cookbook recipes. 
  9  """ 
 10   
 11  # based on Python Cookbook recipe 5.11 -- OK for new- and old-style classes 
12 -def empty_obj(klass):
13 class Empty(klass): 14 def __init__(self) : pass
15 newcopy = Empty() 16 newcopy.__class__ = klass 17 return newcopy 18 19 # create a class based on klass but which may create empty objects 20 # based on Python Cookbook recipe 5.11 -- OK for new- and old-style classes
21 -def empty_class(klass):
22 class _Empty(klass): 23 def __init__(self) : pass
24 return _Empty 25 26 # remove the duplicates from a list. From the Python cook book recipe 17.3 27
28 -def unique(s):
29 """Return a list of elements in s in arbitrary order, but without 30 duplicates. """ 31 32 # get the special case of an empty list 33 n=len(s) 34 if n == 0: 35 return [] 36 37 # try to use a dict 38 u={} 39 try: 40 for x in s: 41 u[x]=1 42 except TypeError: 43 del u # move on th the next method 44 else: 45 return u.keys() 46 47 # Sort to bring duplicate elements together and weed out the 48 # duplcates in on sinle pass 49 try: 50 t=list(s) 51 t.sort() 52 except TypeError: 53 del t # move on to the next method 54 else: 55 assert n > 0 56 last = t[0] 57 lasti = i = 1 58 while i < n: 59 if t[i] != last: 60 t[lasti] = last = t[i] 61 lasti+= 1 62 i += 1 63 return t[:lasti] 64 65 # Brute foce 66 u=[] 67 for x in s: 68 if x not in u: 69 u.append(x) 70 return u
71 72 # based on Python Cookbook recipe 1.12 -- OK for python2.2 and greater
73 -def canLoopOver(maybeIterable):
74 try: 75 iter(maybeIterable) 76 except: return 0 77 else: return 1
78
79 -def isStringLike(obj):
80 try: obj+'' 81 except TypeError: return 0 82 else: return 1
83 84
85 -def containsGangaObjects(obj):
86 """Recursive call to find GangaObjects""" 87 from Ganga.GPIDev.Base.Proxy import isType 88 from Ganga.GPIDev.Base.Objects import GangaObject 89 if not isStringLike(obj) and canLoopOver(obj): 90 for o in obj: 91 if containsGangaObjects(o): 92 return True 93 elif isType(obj,GangaObject): 94 #order is special here as we ignore GangaLists 95 return True 96 return False
97
98 -def isNestedList(obj):
99 if not isStringLike(obj) and canLoopOver(obj): 100 for o in obj: 101 if not isStringLike(o) and canLoopOver(o): 102 return True 103 return False
104 105 # ------------------------ 106 107 __executed_frames = {} 108
109 -def execute_once():
110 """ Return True if this function was not yet executed from a certain line in the program code. 111 Example: 112 execute_once() # -> True 113 execute_once() # -> True 114 115 for i in range(2): 116 execute_once() # -> True (1st), False (2nd) 117 118 if execute_once() and execute_once(): # -> False 119 """ 120 import inspect 121 122 frame = inspect.stack()[1] 123 fid = hash((frame[1],frame[2],frame[3],tuple(frame[4]),frame[5])) 124 del frame 125 if fid in __executed_frames: 126 return False 127 __executed_frames[fid] = 1 128 return True
129 130 # ------------------------ 131
132 -def hostname():
133 """ Try to get the hostname in the most possible reliable way as described in the Python LibRef.""" 134 import socket 135 try: 136 return socket.gethostbyaddr(socket.gethostname())[0] 137 # [bugfix #20333]: 138 # while working offline and with an improper /etc/hosts configuration 139 # the localhost cannot be resolved 140 except: 141 return 'localhost'
142 # ------------------------ 143
144 -class Borg( object ):
145 """ 146 *Python Cookbook recipe 6.16* 147 Borg implementation 148 """ 149 _shared_state = {}
150 - def __new__( cls, *args, **kw ):
151 obj = object.__new__( cls, *args, **kw ) 152 obj.__dict__ = cls._shared_state 153 return obj
154
155 - def __eq__( self, other ):
156 try: 157 return self.__dict__ is other.__dict__ 158 except AttributeError: 159 return False
160
161 - def __hash__( self ):
162 return 0
163 164 # ------------------------ 165
166 -def setAttributesFromDict( d, prefix = None ):
167 """ 168 *Python Cookbook recipe 6.18* 169 Helper function to automatically initialises instance variables 170 from __init_ arguments. 171 """ 172 if prefix is None: 173 prefix = '' 174 self = d.pop( 'self' ) 175 for n, v in d.iteritems(): 176 setattr( self, prefix + n, v )
177 178 179 # ------------------------ 180
181 -def wrap_callable( any_callable, before, after ):
182 def _wrapped( *args, **kwargs ): 183 before() 184 try: 185 return any_callable( *args, **kwargs ) 186 finally: 187 after()
188 return _wrapped 189
190 -def wrap_callable_filter( any_callable, before, after ):
191 def _wrapped( *args, **kwargs ): 192 print 'wrap_callable_filter', args,kwargs 193 args,kwargs = before(list(args),kwargs) 194 try: 195 return any_callable( *args, **kwargs ) 196 finally: 197 after()
198 return _wrapped 199
200 -class GenericWrapper( object ):
201 - def __init__( self, obj, before, after, ignore = (), forced = (), wrapper_function=wrap_callable):
202 classname = 'GenericWrapper' 203 self.__dict__[ '_%s__methods' % classname ] = {} 204 self.__dict__[ '_%s__obj' % classname ] = obj 205 import inspect 206 for name, method in inspect.getmembers( obj, inspect.ismethod ): 207 if name not in ignore and method not in ignore: 208 if forced and (name in forced or method in forced): 209 self.__methods[ name ] = wrapper_function( method, before, after )
210
211 - def __getattr__( self, name ):
212 try: 213 return self.__methods[ name ] 214 except KeyError: 215 return getattr( self.__obj, name )
216
217 - def __setattr__( self, name, value ):
218 setattr( self.__obj, name, value )
219 220 # ------------------------ 221
222 -class Proxy( object ):
223 - def __init__( self, obj ):
224 super( Proxy, self ).__init__( obj ) 225 self._obj = obj
226
227 - def __getattr__( self, attrib ):
228 return getattr( self._obj, attrib )
229
230 -def make_binder( unbounded_method ):
231 def f( self, *a, **k ): return unbounded_method( self._obj, *a, **k ) 232 return f
233 234 known_proxy_classes = {} 235
236 -def proxy( obj, *specials ):
237 obj_cls = obj.__class__ 238 key = obj_cls, specials 239 cls = known_proxy_classes.get( key ) 240 if cls is None: 241 cls = type( "%sProxy" % obj_cls.__name__, ( Proxy, ), {} ) 242 for name in specials: 243 name = '__%s__' % name 244 unbounded_method = getattr( obj_cls, name ) 245 setattr( cls, name, make_binder( unbounded_method ) ) 246 known_proxy_classes[ key ] = cls 247 return cls( obj )
248 249 # ------------------------ 250 # cookbook recipe
251 -def importName(modulename,name):
252 try: 253 module = __import__(modulename,globals(),locals(),[name]) 254 except ImportError: 255 return None 256 try: 257 return vars(module)[name] 258 except KeyError: 259 return None
260 # ------------------------ 261
262 -class IList:
263 """ 264 Proxy class for list objects that enables breaking the elements iteration if the 265 condition flag (sentinel) is set to False during this process 266 All the other operations are delegated to the list object itself 267 #note: the same functionality could be achieved by extending list object 268 #and overriding the __iter__() method but unfortunately this is not exposed in Python2.2 269 #TODO: review this implementation in a more OO way when min Python version in Ganga is 2.3 270 """
271 - def __init__(self, list, sentinel):
272 self._list = list 273 self.sentinel=sentinel 274 self.iterator=None
275
276 - def next(self):
277 if self.sentinel.isSet(): 278 raise StopIteration 279 return self.iterator.next()
280
281 - def __myiter__(self):
282 return self
283
284 - def __getattr__(self, attrib):
285 if attrib=='__iter__': 286 self.iterator=iter(self._list) 287 return getattr(self, '__myiter__') 288 return getattr(self._list, attrib)
289 290 291 if __name__ == "__main__": 292 import Ganga.Utility.logic as logic 293 294 assert(execute_once()) 295 assert(execute_once()) 296 297 if execute_once() and execute_once(): 298 assert(0) 299 300 for i in range(5): 301 assert(logic.equivalent(execute_once(),i==0)) 302 303 print "TestOK" 304 305 # 306 # 307 # $Log: not supported by cvs2svn $ 308 # Revision 1.11.4.3 2008/03/12 17:31:29 moscicki 309 # simplified recursion 310 # 311 # Revision 1.11.4.2 2008/03/12 12:42:39 wreece 312 # Updates the splitters to check for File objects in the list 313 # 314 # Revision 1.11.4.1 2007/12/18 09:08:19 moscicki 315 # factored out the importName cookbook recipe (for integrated typesystem from Alvin) 316 # 317 # Revision 1.11 2007/07/27 14:31:56 moscicki 318 # credential and clean shutdown updates from Adrian (from Ganga-4-4-0-dev-branch) 319 # 320 # Revision 1.10.2.1 2007/07/27 08:46:07 amuraru 321 # clean shutdown update 322 # 323 # Revision 1.10 2007/01/25 16:30:41 moscicki 324 # mergefrom_Ganga-4-2-2-bugfix-branch_25Jan07 (GangaBase-4-14) 325 # 326 # Revision 1.9 2006/10/27 15:15:27 amuraru 327 # [bugfix #20333] 328 # 329 # Revision 1.8.2.1 2006/10/27 15:31:08 amuraru 330 # Bugfix #20545 331 # 332 # Revision 1.9 2006/10/27 15:15:27 amuraru 333 # [bugfix #20333] 334 # 335 # Revision 1.8 2006/07/31 12:19:03 moscicki 336 # added callable filter wrapper 337 # 338 # Revision 1.7 2006/07/10 14:03:28 moscicki 339 # added many Cookbook patterns from Alvin 340 # 341 # Revision 1.6 2006/02/10 15:08:06 moscicki 342 # hostname 343 # 344 # Revision 1.5 2006/01/09 16:41:44 moscicki 345 # execute_once() function used to issue LEGACY warnings 346 # 347 # Revision 1.4 2005/11/01 16:40:04 moscicki 348 # isStringLike 349 # 350 # Revision 1.3 2005/11/01 14:05:21 moscicki 351 # canLoopOver 352 # 353 # Revision 1.2 2005/10/06 09:51:58 andrew 354 # Added the unique method for clearing out duplicates in a list 355 # (Python Cook book recipe 17.3) 356 # 357 # 358 # 359