3 from __future__ import with_statement
19 def printfmt(template):
21 This hides having to create the Template object and call substitute/safe_substitute on it. For example:
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
28 frame = inspect.stack()[-1][0]
30 print string.Template(template).safe_substitute(frame.f_locals)
36 return name.startswith("__") and name.endswith("__")
40 return name.startswith("_") and not is_special(name)
43 def privatize(clsName, attributeName):
45 At runtime, make an attributeName private
48 >>> class Test(object):
52 ... dir(Test).index("_Test__me")
57 >>> setattr(Test, privatize(Test.__name__, "me"), "Hello World")
59 ... dir(Test).index("_Test__me")
65 >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
68 >>> is_private(privatize(Test.__name__, "me"))
70 >>> is_special(privatize(Test.__name__, "me"))
73 return "".join(["_", clsName, "__", attributeName])
76 def obfuscate(clsName, attributeName):
78 At runtime, turn a private name into the obfuscated form
81 >>> class Test(object):
82 ... __me = "Hello World"
85 ... dir(Test).index("_Test__me")
91 >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
93 >>> is_private(obfuscate(Test.__name__, "__me"))
95 >>> is_special(obfuscate(Test.__name__, "__me"))
98 return "".join(["_", clsName, attributeName])
101 class PAOptionParser(optparse.OptionParser, object):
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
117 python mycp.py foo bar
119 python mycp.py foo bar lava
120 Usage: pa.py <Foo> <Bar> <Language> [options]
122 Positional Arguments:
127 pa.py: error: option --Language: invalid choice: 'lava' (choose from 'Python', 'Other'
130 def __init__(self, *args, **kw):
132 super(PAOptionParser, self).__init__(*args, **kw)
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))
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)
145 def parse_args(self, *args, **kwargs):
148 for p, v in zip(self.posargs, args):
149 args0.append("--%s" % p[0])
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):])
159 def explicitly(name, stackadd=0):
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}.
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
169 packageVars = sys._getframe(1+stackadd).f_locals
170 globalAll = packageVars.setdefault('__all__', [])
171 globalAll.append(name)
176 This is a decorator, for convenience. Rather than typing the name of your
177 function twice, you can decorate a function with this.
179 To be real, @public would need to work on methods as well, which gets into
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
186 explicitly(thunk.__name__, 1)
190 def _append_docstring(obj, message):
191 if obj.__doc__ is None:
192 obj.__doc__ = message
194 obj.__doc__ += message
197 def validate_decorator(decorator):
205 f.__dict__["member"] = True
209 if f.__name__ != g.__name__:
210 print f.__name__, "!=", g.__name__
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__
217 if not ("member" in g.__dict__ and g.__dict__["member"]):
218 print "'member' not in ", g.__dict__
221 def deprecated(func):
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.
227 >>> validate_decorator(deprecated)
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")
240 This decorator doesn't add any behavior
242 >>> validate_decorator(enabled)
249 This decorator disables the provided function, and does nothing
251 >>> validate_decorator(disabled)
254 @functools.wraps(func)
255 def emptyFunc(*args, **kargs):
257 _append_docstring(emptyFunc, "\n@note Temporarily Disabled")
261 def metadata(document=True, **kwds):
263 >>> validate_decorator(metadata(author="Ed"))
267 for k, v in kwds.iteritems():
270 _append_docstring(func, "\n@"+k+" "+v)
276 """Function decorator for defining property attributes
278 The decorated function is expected to return a dictionary
279 containing one or more of the following pairs:
280 fget - function for getting attribute value
281 fset - function for setting attribute value
282 fdel - function for deleting attribute
283 This can be conveniently constructed by the locals() builtin
285 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
286 @author http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html
289 >>> #Due to transformation from function to property, does not need to be validated
290 >>> #validate_decorator(prop)
291 >>> class MyExampleClass(object):
294 ... "The foo property attribute's doc-string"
298 ... def fset(self, value):
300 ... self._foo = value
303 >>> me = MyExampleClass()
310 return property(doc=func.__doc__, **func())
313 def print_handler(e):
317 print "%s: %s" % (type(e).__name__, e)
324 print 'Ignoring %s exception: %s' % (type(e).__name__, e)
327 def print_traceback(e):
331 #print sys.exc_info()
332 traceback.print_exc(file=sys.stdout)
335 def ExpHandler(handler = print_handler, *exceptions):
337 An exception handling idiom using decorators
339 Specify exceptions in order, first one is handled first
342 >>> validate_decorator(ExpHandler())
343 >>> @ExpHandler(print_ignore, ZeroDivisionError)
344 ... @ExpHandler(None, AttributeError, ValueError)
347 >>> @ExpHandler(print_traceback, ZeroDivisionError)
354 >>> @ExpHandler(print_traceback, ZeroDivisionError)
360 Ignoring ZeroDivisionError exception: integer division or modulo by zero
361 >>> f2() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
362 Traceback (most recent call last):
364 ZeroDivisionError: integer division or modulo by zero
366 IndexError: tuple index out of range
372 localExceptions = exceptions
373 if not localExceptions:
374 localExceptions = [Exception]
375 t = [(ex, handler) for ex in localExceptions]
378 def newfunc(t, *args, **kwargs):
382 return f(*args, **kwargs)
384 #Recurse for embedded try/excepts
385 dec_func = functools.partial(newfunc, t[1:])
386 dec_func = functools.update_wrapper(dec_func, f)
387 return dec_func(*args, **kwargs)
391 dec_func = functools.partial(newfunc, t)
392 dec_func = functools.update_wrapper(dec_func, f)
397 class bindclass(object):
399 >>> validate_decorator(bindclass)
400 >>> class Foo(BoundObject):
402 ... def foo(this_class, self):
403 ... return this_class, self
407 ... def bar(this_class, self):
408 ... return this_class, self
413 >>> f.foo() # doctest: +ELLIPSIS
414 (<class '...Foo'>, <...Foo object at ...>)
415 >>> b.foo() # doctest: +ELLIPSIS
416 (<class '...Foo'>, <...Bar object at ...>)
417 >>> b.bar() # doctest: +ELLIPSIS
418 (<class '...Bar'>, <...Bar object at ...>)
421 def __init__(self, f):
423 self.__name__ = f.__name__
424 self.__doc__ = f.__doc__
425 self.__dict__.update(f.__dict__)
428 def bind(self, cls, attr):
430 def bound_m(*args, **kwargs):
431 return self.f(cls, *args, **kwargs)
432 bound_m.__name__ = attr
435 def __get__(self, obj, objtype=None):
436 return self.m.__get__(obj, objtype)
439 class ClassBindingSupport(type):
442 def __init__(mcs, name, bases, attrs):
443 type.__init__(mcs, name, bases, attrs)
444 for attr, val in attrs.iteritems():
445 if isinstance(val, bindclass):
449 class BoundObject(object):
451 __metaclass__ = ClassBindingSupport
456 >>> validate_decorator(bindfunction)
458 ... def factorial(thisfunction, n):
459 ... # Within this function the name 'thisfunction' refers to the factorial
460 ... # function(with only one argument), even after 'factorial' is bound
461 ... # to another object
463 ... return n * thisfunction(n - 1)
472 def bound_f(*args, **kwargs):
473 return f(bound_f, *args, **kwargs)
477 class Memoize(object):
479 Memoize(fn) - an instance which acts like fn but memoizes its arguments
480 Will only work on functions with non-mutable arguments
481 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
483 >>> validate_decorator(Memoize)
486 def __init__(self, fn):
488 self.__name__ = fn.__name__
489 self.__doc__ = fn.__doc__
490 self.__dict__.update(fn.__dict__)
493 def __call__(self, *args):
494 if args not in self.memo:
495 self.memo[args] = self.fn(*args)
496 return self.memo[args]
499 class MemoizeMutable(object):
500 """Memoize(fn) - an instance which acts like fn but memoizes its arguments
501 Will work on functions with mutable arguments(slower than Memoize)
502 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
504 >>> validate_decorator(MemoizeMutable)
507 def __init__(self, fn):
509 self.__name__ = fn.__name__
510 self.__doc__ = fn.__doc__
511 self.__dict__.update(fn.__dict__)
514 def __call__(self, *args, **kw):
515 text = cPickle.dumps((args, kw))
516 if text not in self.memo:
517 self.memo[text] = self.fn(*args, **kw)
518 return self.memo[text]
521 callTraceIndentationLevel = 0
526 Synchronization decorator.
528 >>> validate_decorator(call_trace)
533 Entering a((1, 2), {'c': 3})
534 Exiting a((1, 2), {'c': 3})
538 def verboseTrace(*args, **kw):
539 global callTraceIndentationLevel
541 print "%sEntering %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
542 callTraceIndentationLevel += 1
544 result = f(*args, **kw)
546 callTraceIndentationLevel -= 1
547 print "%sException %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
549 callTraceIndentationLevel -= 1
550 print "%sExiting %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
554 def smallTrace(*args, **kw):
555 global callTraceIndentationLevel
557 print "%sEntering %s" % ("\t"*callTraceIndentationLevel, f.__name__)
558 callTraceIndentationLevel += 1
560 result = f(*args, **kw)
562 callTraceIndentationLevel -= 1
563 print "%sException %s" % ("\t"*callTraceIndentationLevel, f.__name__)
565 callTraceIndentationLevel -= 1
566 print "%sExiting %s" % ("\t"*callTraceIndentationLevel, f.__name__)
573 @contextlib.contextmanager
574 def lexical_scope(*args):
576 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/520586
579 >>> with lexical_scope(1) as (a):
583 >>> with lexical_scope(1,2,3) as (a,b,c):
587 >>> with lexical_scope():
596 frame = inspect.currentframe().f_back.f_back
597 saved = frame.f_locals.keys()
606 f_locals = frame.f_locals
607 for key in (x for x in f_locals.keys() if x not in saved):