1
2
3
4
5
6
7 """
8 This file contains general-purpose utilities, mainly Python Cookbook recipes.
9 """
10
11
13 class Empty(klass):
14 def __init__(self) : pass
15 newcopy = Empty()
16 newcopy.__class__ = klass
17 return newcopy
18
19
20
22 class _Empty(klass):
23 def __init__(self) : pass
24 return _Empty
25
26
27
29 """Return a list of elements in s in arbitrary order, but without
30 duplicates. """
31
32
33 n=len(s)
34 if n == 0:
35 return []
36
37
38 u={}
39 try:
40 for x in s:
41 u[x]=1
42 except TypeError:
43 del u
44 else:
45 return u.keys()
46
47
48
49 try:
50 t=list(s)
51 t.sort()
52 except TypeError:
53 del t
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
66 u=[]
67 for x in s:
68 if x not in u:
69 u.append(x)
70 return u
71
72
74 try:
75 iter(maybeIterable)
76 except: return 0
77 else: return 1
78
80 try: obj+''
81 except TypeError: return 0
82 else: return 1
83
84
97
104
105
106
107 __executed_frames = {}
108
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
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
138
139
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 = {}
154
156 try:
157 return self.__dict__ is other.__dict__
158 except AttributeError:
159 return False
160
163
164
165
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
182 def _wrapped( *args, **kwargs ):
183 before()
184 try:
185 return any_callable( *args, **kwargs )
186 finally:
187 after()
188 return _wrapped
189
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
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
212 try:
213 return self.__methods[ name ]
214 except KeyError:
215 return getattr( self.__obj, name )
216
218 setattr( self.__obj, name, value )
219
220
221
226
228 return getattr( self._obj, attrib )
229
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 ):
248
249
250
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
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 """
272 self._list = list
273 self.sentinel=sentinel
274 self.iterator=None
275
277 if self.sentinel.isSet():
278 raise StopIteration
279 return self.iterator.next()
280
283
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359