Getting start on this here em code
[theonering] / src / util / misc.py
1 #!/usr/bin/env python
2
3 from __future__ import with_statement
4
5 import sys
6 import cPickle
7
8 import functools
9 import itertools
10 import contextlib
11 import inspect
12
13 import optparse
14 import traceback
15 import warnings
16 import string
17
18
19 def printfmt(template):
20         """
21         This hides having to create the Template object and call substitute/safe_substitute on it. For example:
22
23         >>> num = 10
24         >>> word = "spam"
25         >>> printfmt("I would like to order $num units of $word, please") #doctest: +SKIP
26         I would like to order 10 units of spam, please
27         """
28         frame = inspect.stack()[-1][0]
29         try:
30                 print string.Template(template).safe_substitute(frame.f_locals)
31         finally:
32                 del frame
33
34
35 def is_special(name):
36         return name.startswith("__") and name.endswith("__")
37
38
39 def is_private(name):
40         return name.startswith("_") and not is_special(name)
41
42
43 def privatize(clsName, attributeName):
44         """
45         At runtime, make an attributeName private
46
47         Example:
48         >>> class Test(object):
49         ...     pass
50         ...
51         >>> try:
52         ...     dir(Test).index("_Test__me")
53         ...     print dir(Test)
54         ... except:
55         ...     print "Not Found"
56         Not Found
57         >>> setattr(Test, privatize(Test.__name__, "me"), "Hello World")
58         >>> try:
59         ...     dir(Test).index("_Test__me")
60         ...     print "Found"
61         ... except:
62         ...     print dir(Test)
63         0
64         Found
65         >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
66         Hello World
67         >>>
68         >>> is_private(privatize(Test.__name__, "me"))
69         True
70         >>> is_special(privatize(Test.__name__, "me"))
71         False
72         """
73         return "".join(["_", clsName, "__", attributeName])
74
75
76 def obfuscate(clsName, attributeName):
77         """
78         At runtime, turn a private name into the obfuscated form
79
80         Example:
81         >>> class Test(object):
82         ...     __me = "Hello World"
83         ...
84         >>> try:
85         ...     dir(Test).index("_Test__me")
86         ...     print "Found"
87         ... except:
88         ...     print dir(Test)
89         0
90         Found
91         >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
92         Hello World
93         >>> is_private(obfuscate(Test.__name__, "__me"))
94         True
95         >>> is_special(obfuscate(Test.__name__, "__me"))
96         False
97         """
98         return "".join(["_", clsName, attributeName])
99
100
101 class PAOptionParser(optparse.OptionParser, object):
102         """
103         >>> if __name__ == '__main__':
104         ...     #parser = PAOptionParser("My usage str")
105         ...     parser = PAOptionParser()
106         ...     parser.add_posarg("Foo", help="Foo usage")
107         ...     parser.add_posarg("Bar", dest="bar_dest")
108         ...     parser.add_posarg("Language", dest='tr_type', type="choice", choices=("Python", "Other"))
109         ...     parser.add_option('--stocksym', dest='symbol')
110         ...     values, args = parser.parse_args()
111         ...     print values, args
112         ...
113
114         python mycp.py  -h
115         python mycp.py
116         python mycp.py  foo
117         python mycp.py  foo bar
118
119         python mycp.py foo bar lava
120         Usage: pa.py <Foo> <Bar> <Language> [options]
121
122         Positional Arguments:
123         Foo: Foo usage
124         Bar:
125         Language:
126
127         pa.py: error: option --Language: invalid choice: 'lava' (choose from 'Python', 'Other'
128         """
129
130         def __init__(self, *args, **kw):
131                 self.posargs = []
132                 super(PAOptionParser, self).__init__(*args, **kw)
133
134         def add_posarg(self, *args, **kw):
135                 pa_help = kw.get("help", "")
136                 kw["help"] = optparse.SUPPRESS_HELP
137                 o = self.add_option("--%s" % args[0], *args[1:], **kw)
138                 self.posargs.append((args[0], pa_help))
139
140         def get_usage(self, *args, **kwargs):
141                 params = (' '.join(["<%s>" % arg[0] for arg in self.posargs]), '\n '.join(["%s: %s" % (arg) for arg in self.posargs]))
142                 self.usage = "%%prog %s [options]\n\nPositional Arguments:\n %s" % params
143                 return super(PAOptionParser, self).get_usage(*args, **kwargs)
144
145         def parse_args(self, *args, **kwargs):
146                 args = sys.argv[1:]
147                 args0 = []
148                 for p, v in zip(self.posargs, args):
149                         args0.append("--%s" % p[0])
150                         args0.append(v)
151                 args = args0 + args
152                 options, args = super(PAOptionParser, self).parse_args(args, **kwargs)
153                 if len(args) < len(self.posargs):
154                         msg = 'Missing value(s) for "%s"\n' % ", ".join([arg[0] for arg in self.posargs][len(args):])
155                         self.error(msg)
156                 return options, args
157
158
159 def explicitly(name, stackadd=0):
160         """
161         This is an alias for adding to '__all__'.  Less error-prone than using
162         __all__ itself, since setting __all__ directly is prone to stomping on
163         things implicitly exported via L{alias}.
164
165         @note Taken from PyExport (which could turn out pretty cool):
166         @li @a http://codebrowse.launchpad.net/~glyph/
167         @li @a http://glyf.livejournal.com/74356.html
168         """
169         packageVars = sys._getframe(1+stackadd).f_locals
170         globalAll = packageVars.setdefault('__all__', [])
171         globalAll.append(name)
172
173
174 def public(thunk):
175         """
176         This is a decorator, for convenience.  Rather than typing the name of your
177         function twice, you can decorate a function with this.
178
179         To be real, @public would need to work on methods as well, which gets into
180         supporting types...
181
182         @note Taken from PyExport (which could turn out pretty cool):
183         @li @a http://codebrowse.launchpad.net/~glyph/
184         @li @a http://glyf.livejournal.com/74356.html
185         """
186         explicitly(thunk.__name__, 1)
187         return thunk
188
189
190 def _append_docstring(obj, message):
191         if obj.__doc__ is None:
192                 obj.__doc__ = message
193         else:
194                 obj.__doc__ += message
195
196
197 def validate_decorator(decorator):
198
199         def simple(x):
200                 return x
201
202         f = simple
203         f.__name__ = "name"
204         f.__doc__ = "doc"
205         f.__dict__["member"] = True
206
207         g = decorator(f)
208
209         if f.__name__ != g.__name__:
210                 print f.__name__, "!=", g.__name__
211
212         if g.__doc__ is None:
213                 print decorator.__name__, "has no doc string"
214         elif not g.__doc__.startswith(f.__doc__):
215                 print g.__doc__, "didn't start with", f.__doc__
216
217         if not ("member" in g.__dict__ and g.__dict__["member"]):
218                 print "'member' not in ", g.__dict__
219
220
221 def deprecated_api(func):
222         """
223         This is a decorator which can be used to mark functions
224         as deprecated. It will result in a warning being emitted
225         when the function is used.
226
227         >>> validate_decorator(deprecated_api)
228         """
229
230         @functools.wraps(func)
231         def newFunc(*args, **kwargs):
232                 warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning)
233                 return func(*args, **kwargs)
234         _append_docstring(newFunc, "\n@deprecated")
235         return newFunc
236
237
238 def unstable_api(func):
239         """
240         This is a decorator which can be used to mark functions
241         as deprecated. It will result in a warning being emitted
242         when the function is used.
243
244         >>> validate_decorator(unstable_api)
245         """
246
247         @functools.wraps(func)
248         def newFunc(*args, **kwargs):
249                 warnings.warn("Call to unstable API function %s." % func.__name__, category=FutureWarning)
250                 return func(*args, **kwargs)
251         _append_docstring(newFunc, "\n@unstable")
252         return newFunc
253
254
255 def enabled(func):
256         """
257         This decorator doesn't add any behavior
258
259         >>> validate_decorator(enabled)
260         """
261         return func
262
263
264 def disabled(func):
265         """
266         This decorator disables the provided function, and does nothing
267
268         >>> validate_decorator(disabled)
269         """
270
271         @functools.wraps(func)
272         def emptyFunc(*args, **kargs):
273                 pass
274         _append_docstring(emptyFunc, "\n@note Temporarily Disabled")
275         return emptyFunc
276
277
278 def metadata(document=True, **kwds):
279         """
280         >>> validate_decorator(metadata(author="Ed"))
281         """
282
283         def decorate(func):
284                 for k, v in kwds.iteritems():
285                         setattr(func, k, v)
286                         if document:
287                                 _append_docstring(func, "\n@"+k+" "+v)
288                 return func
289         return decorate
290
291
292 def prop(func):
293         """Function decorator for defining property attributes
294
295         The decorated function is expected to return a dictionary
296         containing one or more of the following pairs:
297                 fget - function for getting attribute value
298                 fset - function for setting attribute value
299                 fdel - function for deleting attribute
300         This can be conveniently constructed by the locals() builtin
301         function; see:
302         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
303         @author http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html
304
305         Example:
306         >>> #Due to transformation from function to property, does not need to be validated
307         >>> #validate_decorator(prop)
308         >>> class MyExampleClass(object):
309         ...     @prop
310         ...     def foo():
311         ...             "The foo property attribute's doc-string"
312         ...             def fget(self):
313         ...                     print "GET"
314         ...                     return self._foo
315         ...             def fset(self, value):
316         ...                     print "SET"
317         ...                     self._foo = value
318         ...             return locals()
319         ...
320         >>> me = MyExampleClass()
321         >>> me.foo = 10
322         SET
323         >>> print me.foo
324         GET
325         10
326         """
327         return property(doc=func.__doc__, **func())
328
329
330 def print_handler(e):
331         """
332         @see ExpHandler
333         """
334         print "%s: %s" % (type(e).__name__, e)
335
336
337 def print_ignore(e):
338         """
339         @see ExpHandler
340         """
341         print 'Ignoring %s exception: %s' % (type(e).__name__, e)
342
343
344 def print_traceback(e):
345         """
346         @see ExpHandler
347         """
348         #print sys.exc_info()
349         traceback.print_exc(file=sys.stdout)
350
351
352 def ExpHandler(handler = print_handler, *exceptions):
353         """
354         An exception handling idiom using decorators
355         Examples
356         Specify exceptions in order, first one is handled first
357         last one last.
358
359         >>> validate_decorator(ExpHandler())
360         >>> @ExpHandler(print_ignore, ZeroDivisionError)
361         ... @ExpHandler(None, AttributeError, ValueError)
362         ... def f1():
363         ...     1/0
364         >>> @ExpHandler(print_traceback, ZeroDivisionError)
365         ... def f2():
366         ...     1/0
367         >>> @ExpHandler()
368         ... def f3(*pargs):
369         ...     l = pargs
370         ...     return l[10]
371         >>> @ExpHandler(print_traceback, ZeroDivisionError)
372         ... def f4():
373         ...     return 1
374         >>>
375         >>>
376         >>> f1()
377         Ignoring ZeroDivisionError exception: integer division or modulo by zero
378         >>> f2() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
379         Traceback (most recent call last):
380         ...
381         ZeroDivisionError: integer division or modulo by zero
382         >>> f3()
383         IndexError: tuple index out of range
384         >>> f4()
385         1
386         """
387
388         def wrapper(f):
389                 localExceptions = exceptions
390                 if not localExceptions:
391                         localExceptions = [Exception]
392                 t = [(ex, handler) for ex in localExceptions]
393                 t.reverse()
394
395                 def newfunc(t, *args, **kwargs):
396                         ex, handler = t[0]
397                         try:
398                                 if len(t) == 1:
399                                         return f(*args, **kwargs)
400                                 else:
401                                         #Recurse for embedded try/excepts
402                                         dec_func = functools.partial(newfunc, t[1:])
403                                         dec_func = functools.update_wrapper(dec_func, f)
404                                         return dec_func(*args, **kwargs)
405                         except ex, e:
406                                 return handler(e)
407
408                 dec_func = functools.partial(newfunc, t)
409                 dec_func = functools.update_wrapper(dec_func, f)
410                 return dec_func
411         return wrapper
412
413
414 class bindclass(object):
415         """
416         >>> validate_decorator(bindclass)
417         >>> class Foo(BoundObject):
418         ...      @bindclass
419         ...      def foo(this_class, self):
420         ...              return this_class, self
421         ...
422         >>> class Bar(Foo):
423         ...      @bindclass
424         ...      def bar(this_class, self):
425         ...              return this_class, self
426         ...
427         >>> f = Foo()
428         >>> b = Bar()
429         >>>
430         >>> f.foo() # doctest: +ELLIPSIS
431         (<class '...Foo'>, <...Foo object at ...>)
432         >>> b.foo() # doctest: +ELLIPSIS
433         (<class '...Foo'>, <...Bar object at ...>)
434         >>> b.bar() # doctest: +ELLIPSIS
435         (<class '...Bar'>, <...Bar object at ...>)
436         """
437
438         def __init__(self, f):
439                 self.f = f
440                 self.__name__ = f.__name__
441                 self.__doc__ = f.__doc__
442                 self.__dict__.update(f.__dict__)
443                 self.m = None
444
445         def bind(self, cls, attr):
446
447                 def bound_m(*args, **kwargs):
448                         return self.f(cls, *args, **kwargs)
449                 bound_m.__name__ = attr
450                 self.m = bound_m
451
452         def __get__(self, obj, objtype=None):
453                 return self.m.__get__(obj, objtype)
454
455
456 class ClassBindingSupport(type):
457         "@see bindclass"
458
459         def __init__(mcs, name, bases, attrs):
460                 type.__init__(mcs, name, bases, attrs)
461                 for attr, val in attrs.iteritems():
462                         if isinstance(val, bindclass):
463                                 val.bind(mcs, attr)
464
465
466 class BoundObject(object):
467         "@see bindclass"
468         __metaclass__ = ClassBindingSupport
469
470
471 def bindfunction(f):
472         """
473         >>> validate_decorator(bindfunction)
474         >>> @bindfunction
475         ... def factorial(thisfunction, n):
476         ...      # Within this function the name 'thisfunction' refers to the factorial
477         ...      # function(with only one argument), even after 'factorial' is bound
478         ...      # to another object
479         ...      if n > 0:
480         ...              return n * thisfunction(n - 1)
481         ...      else:
482         ...              return 1
483         ...
484         >>> factorial(3)
485         6
486         """
487
488         @functools.wraps(f)
489         def bound_f(*args, **kwargs):
490                 return f(bound_f, *args, **kwargs)
491         return bound_f
492
493
494 class Memoize(object):
495         """
496         Memoize(fn) - an instance which acts like fn but memoizes its arguments
497         Will only work on functions with non-mutable arguments
498         @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
499
500         >>> validate_decorator(Memoize)
501         """
502
503         def __init__(self, fn):
504                 self.fn = fn
505                 self.__name__ = fn.__name__
506                 self.__doc__ = fn.__doc__
507                 self.__dict__.update(fn.__dict__)
508                 self.memo = {}
509
510         def __call__(self, *args):
511                 if args not in self.memo:
512                         self.memo[args] = self.fn(*args)
513                 return self.memo[args]
514
515
516 class MemoizeMutable(object):
517         """Memoize(fn) - an instance which acts like fn but memoizes its arguments
518         Will work on functions with mutable arguments(slower than Memoize)
519         @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
520
521         >>> validate_decorator(MemoizeMutable)
522         """
523
524         def __init__(self, fn):
525                 self.fn = fn
526                 self.__name__ = fn.__name__
527                 self.__doc__ = fn.__doc__
528                 self.__dict__.update(fn.__dict__)
529                 self.memo = {}
530
531         def __call__(self, *args, **kw):
532                 text = cPickle.dumps((args, kw))
533                 if text not in self.memo:
534                         self.memo[text] = self.fn(*args, **kw)
535                 return self.memo[text]
536
537
538 callTraceIndentationLevel = 0
539
540
541 def call_trace(f):
542         """
543         Synchronization decorator.
544
545         >>> validate_decorator(call_trace)
546         >>> @call_trace
547         ... def a(a, b, c):
548         ...     pass
549         >>> a(1, 2, c=3)
550         Entering a((1, 2), {'c': 3})
551         Exiting a((1, 2), {'c': 3})
552         """
553
554         @functools.wraps(f)
555         def verboseTrace(*args, **kw):
556                 global callTraceIndentationLevel
557
558                 print "%sEntering %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
559                 callTraceIndentationLevel += 1
560                 try:
561                         result = f(*args, **kw)
562                 except:
563                         callTraceIndentationLevel -= 1
564                         print "%sException %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
565                         raise
566                 callTraceIndentationLevel -= 1
567                 print "%sExiting %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
568                 return result
569
570         @functools.wraps(f)
571         def smallTrace(*args, **kw):
572                 global callTraceIndentationLevel
573
574                 print "%sEntering %s" % ("\t"*callTraceIndentationLevel, f.__name__)
575                 callTraceIndentationLevel += 1
576                 try:
577                         result = f(*args, **kw)
578                 except:
579                         callTraceIndentationLevel -= 1
580                         print "%sException %s" % ("\t"*callTraceIndentationLevel, f.__name__)
581                         raise
582                 callTraceIndentationLevel -= 1
583                 print "%sExiting %s" % ("\t"*callTraceIndentationLevel, f.__name__)
584                 return result
585
586         #return smallTrace
587         return verboseTrace
588
589
590 @contextlib.contextmanager
591 def lexical_scope(*args):
592         """
593         @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/520586
594         Example:
595         >>> b = 0
596         >>> with lexical_scope(1) as (a):
597         ...     print a
598         ...
599         1
600         >>> with lexical_scope(1,2,3) as (a,b,c):
601         ...     print a,b,c
602         ...
603         1 2 3
604         >>> with lexical_scope():
605         ...     d = 10
606         ...     def foo():
607         ...             pass
608         ...
609         >>> print b
610         2
611         """
612
613         frame = inspect.currentframe().f_back.f_back
614         saved = frame.f_locals.keys()
615         try:
616                 if not args:
617                         yield
618                 elif len(args) == 1:
619                         yield args[0]
620                 else:
621                         yield args
622         finally:
623                 f_locals = frame.f_locals
624                 for key in (x for x in f_locals.keys() if x not in saved):
625                         del f_locals[key]
626                 del frame