3 from __future__ import with_statement
18 def printfmt(template):
20 This hides having to create the Template object and call substitute/safe_substitute on it. For example:
24 >>> printfmt("I would like to order $num units of $word, please") #doctest: +SKIP
25 I would like to order 10 units of spam, please
27 frame = inspect.stack()[-1][0]
29 print string.Template(template).safe_substitute(frame.f_locals)
35 return name.startswith("__") and name.endswith("__")
39 return name.startswith("_") and not is_special(name)
42 def privatize(clsName, attributeName):
44 At runtime, make an attributeName private
47 >>> class Test(object):
51 ... dir(Test).index("_Test__me")
56 >>> setattr(Test, privatize(Test.__name__, "me"), "Hello World")
58 ... dir(Test).index("_Test__me")
64 >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
67 >>> is_private(privatize(Test.__name__, "me"))
69 >>> is_special(privatize(Test.__name__, "me"))
72 return "".join(["_", clsName, "__", attributeName])
75 def obfuscate(clsName, attributeName):
77 At runtime, turn a private name into the obfuscated form
80 >>> class Test(object):
81 ... __me = "Hello World"
84 ... dir(Test).index("_Test__me")
90 >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
92 >>> is_private(obfuscate(Test.__name__, "__me"))
94 >>> is_special(obfuscate(Test.__name__, "__me"))
97 return "".join(["_", clsName, attributeName])
100 class PAOptionParser(optparse.OptionParser, object):
102 >>> if __name__ == '__main__':
103 ... #parser = PAOptionParser("My usage str")
104 ... parser = PAOptionParser()
105 ... parser.add_posarg("Foo", help="Foo usage")
106 ... parser.add_posarg("Bar", dest="bar_dest")
107 ... parser.add_posarg("Language", dest='tr_type', type="choice", choices=("Python", "Other"))
108 ... parser.add_option('--stocksym', dest='symbol')
109 ... values, args = parser.parse_args()
110 ... print values, args
116 python mycp.py foo bar
118 python mycp.py foo bar lava
119 Usage: pa.py <Foo> <Bar> <Language> [options]
121 Positional Arguments:
126 pa.py: error: option --Language: invalid choice: 'lava' (choose from 'Python', 'Other'
129 def __init__(self, *args, **kw):
131 super(PAOptionParser, self).__init__(*args, **kw)
133 def add_posarg(self, *args, **kw):
134 pa_help = kw.get("help", "")
135 kw["help"] = optparse.SUPPRESS_HELP
136 o = self.add_option("--%s" % args[0], *args[1:], **kw)
137 self.posargs.append((args[0], pa_help))
139 def get_usage(self, *args, **kwargs):
140 params = (' '.join(["<%s>" % arg[0] for arg in self.posargs]), '\n '.join(["%s: %s" % (arg) for arg in self.posargs]))
141 self.usage = "%%prog %s [options]\n\nPositional Arguments:\n %s" % params
142 return super(PAOptionParser, self).get_usage(*args, **kwargs)
144 def parse_args(self, *args, **kwargs):
147 for p, v in zip(self.posargs, args):
148 args0.append("--%s" % p[0])
151 options, args = super(PAOptionParser, self).parse_args(args, **kwargs)
152 if len(args) < len(self.posargs):
153 msg = 'Missing value(s) for "%s"\n' % ", ".join([arg[0] for arg in self.posargs][len(args):])
158 def explicitly(name, stackadd=0):
160 This is an alias for adding to '__all__'. Less error-prone than using
161 __all__ itself, since setting __all__ directly is prone to stomping on
162 things implicitly exported via L{alias}.
164 @note Taken from PyExport (which could turn out pretty cool):
165 @li @a http://codebrowse.launchpad.net/~glyph/
166 @li @a http://glyf.livejournal.com/74356.html
168 packageVars = sys._getframe(1+stackadd).f_locals
169 globalAll = packageVars.setdefault('__all__', [])
170 globalAll.append(name)
175 This is a decorator, for convenience. Rather than typing the name of your
176 function twice, you can decorate a function with this.
178 To be real, @public would need to work on methods as well, which gets into
181 @note Taken from PyExport (which could turn out pretty cool):
182 @li @a http://codebrowse.launchpad.net/~glyph/
183 @li @a http://glyf.livejournal.com/74356.html
185 explicitly(thunk.__name__, 1)
189 def _append_docstring(obj, message):
190 if obj.__doc__ is None:
191 obj.__doc__ = message
193 obj.__doc__ += message
196 def validate_decorator(decorator):
204 f.__dict__["member"] = True
208 if f.__name__ != g.__name__:
209 print f.__name__, "!=", g.__name__
211 if g.__doc__ is None:
212 print decorator.__name__, "has no doc string"
213 elif not g.__doc__.startswith(f.__doc__):
214 print g.__doc__, "didn't start with", f.__doc__
216 if not ("member" in g.__dict__ and g.__dict__["member"]):
217 print "'member' not in ", g.__dict__
220 def deprecated_api(func):
222 This is a decorator which can be used to mark functions
223 as deprecated. It will result in a warning being emitted
224 when the function is used.
226 >>> validate_decorator(deprecated_api)
229 @functools.wraps(func)
230 def newFunc(*args, **kwargs):
231 warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning)
232 return func(*args, **kwargs)
233 _append_docstring(newFunc, "\n@deprecated")
237 def unstable_api(func):
239 This is a decorator which can be used to mark functions
240 as deprecated. It will result in a warning being emitted
241 when the function is used.
243 >>> validate_decorator(unstable_api)
246 @functools.wraps(func)
247 def newFunc(*args, **kwargs):
248 warnings.warn("Call to unstable API function %s." % func.__name__, category=FutureWarning)
249 return func(*args, **kwargs)
250 _append_docstring(newFunc, "\n@unstable")
256 This decorator doesn't add any behavior
258 >>> validate_decorator(enabled)
265 This decorator disables the provided function, and does nothing
267 >>> validate_decorator(disabled)
270 @functools.wraps(func)
271 def emptyFunc(*args, **kargs):
273 _append_docstring(emptyFunc, "\n@note Temporarily Disabled")
277 def metadata(document=True, **kwds):
279 >>> validate_decorator(metadata(author="Ed"))
283 for k, v in kwds.iteritems():
286 _append_docstring(func, "\n@"+k+" "+v)
292 """Function decorator for defining property attributes
294 The decorated function is expected to return a dictionary
295 containing one or more of the following pairs:
296 fget - function for getting attribute value
297 fset - function for setting attribute value
298 fdel - function for deleting attribute
299 This can be conveniently constructed by the locals() builtin
301 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
302 @author http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html
305 >>> #Due to transformation from function to property, does not need to be validated
306 >>> #validate_decorator(prop)
307 >>> class MyExampleClass(object):
310 ... "The foo property attribute's doc-string"
314 ... def fset(self, value):
316 ... self._foo = value
319 >>> me = MyExampleClass()
326 return property(doc=func.__doc__, **func())
329 def print_handler(e):
333 print "%s: %s" % (type(e).__name__, e)
340 print 'Ignoring %s exception: %s' % (type(e).__name__, e)
343 def print_traceback(e):
347 #print sys.exc_info()
348 traceback.print_exc(file=sys.stdout)
351 def ExpHandler(handler = print_handler, *exceptions):
353 An exception handling idiom using decorators
355 Specify exceptions in order, first one is handled first
358 >>> validate_decorator(ExpHandler())
359 >>> @ExpHandler(print_ignore, ZeroDivisionError)
360 ... @ExpHandler(None, AttributeError, ValueError)
363 >>> @ExpHandler(print_traceback, ZeroDivisionError)
370 >>> @ExpHandler(print_traceback, ZeroDivisionError)
376 Ignoring ZeroDivisionError exception: integer division or modulo by zero
377 >>> f2() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
378 Traceback (most recent call last):
380 ZeroDivisionError: integer division or modulo by zero
382 IndexError: tuple index out of range
388 localExceptions = exceptions
389 if not localExceptions:
390 localExceptions = [Exception]
391 t = [(ex, handler) for ex in localExceptions]
394 def newfunc(t, *args, **kwargs):
398 return f(*args, **kwargs)
400 #Recurse for embedded try/excepts
401 dec_func = functools.partial(newfunc, t[1:])
402 dec_func = functools.update_wrapper(dec_func, f)
403 return dec_func(*args, **kwargs)
407 dec_func = functools.partial(newfunc, t)
408 dec_func = functools.update_wrapper(dec_func, f)
413 class bindclass(object):
415 >>> validate_decorator(bindclass)
416 >>> class Foo(BoundObject):
418 ... def foo(this_class, self):
419 ... return this_class, self
423 ... def bar(this_class, self):
424 ... return this_class, self
429 >>> f.foo() # doctest: +ELLIPSIS
430 (<class '...Foo'>, <...Foo object at ...>)
431 >>> b.foo() # doctest: +ELLIPSIS
432 (<class '...Foo'>, <...Bar object at ...>)
433 >>> b.bar() # doctest: +ELLIPSIS
434 (<class '...Bar'>, <...Bar object at ...>)
437 def __init__(self, f):
439 self.__name__ = f.__name__
440 self.__doc__ = f.__doc__
441 self.__dict__.update(f.__dict__)
444 def bind(self, cls, attr):
446 def bound_m(*args, **kwargs):
447 return self.f(cls, *args, **kwargs)
448 bound_m.__name__ = attr
451 def __get__(self, obj, objtype=None):
452 return self.m.__get__(obj, objtype)
455 class ClassBindingSupport(type):
458 def __init__(mcs, name, bases, attrs):
459 type.__init__(mcs, name, bases, attrs)
460 for attr, val in attrs.iteritems():
461 if isinstance(val, bindclass):
465 class BoundObject(object):
467 __metaclass__ = ClassBindingSupport
472 >>> validate_decorator(bindfunction)
474 ... def factorial(thisfunction, n):
475 ... # Within this function the name 'thisfunction' refers to the factorial
476 ... # function(with only one argument), even after 'factorial' is bound
477 ... # to another object
479 ... return n * thisfunction(n - 1)
488 def bound_f(*args, **kwargs):
489 return f(bound_f, *args, **kwargs)
493 class Memoize(object):
495 Memoize(fn) - an instance which acts like fn but memoizes its arguments
496 Will only work on functions with non-mutable arguments
497 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
499 >>> validate_decorator(Memoize)
502 def __init__(self, fn):
504 self.__name__ = fn.__name__
505 self.__doc__ = fn.__doc__
506 self.__dict__.update(fn.__dict__)
509 def __call__(self, *args):
510 if args not in self.memo:
511 self.memo[args] = self.fn(*args)
512 return self.memo[args]
515 class MemoizeMutable(object):
516 """Memoize(fn) - an instance which acts like fn but memoizes its arguments
517 Will work on functions with mutable arguments(slower than Memoize)
518 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
520 >>> validate_decorator(MemoizeMutable)
523 def __init__(self, fn):
525 self.__name__ = fn.__name__
526 self.__doc__ = fn.__doc__
527 self.__dict__.update(fn.__dict__)
530 def __call__(self, *args, **kw):
531 text = cPickle.dumps((args, kw))
532 if text not in self.memo:
533 self.memo[text] = self.fn(*args, **kw)
534 return self.memo[text]
537 callTraceIndentationLevel = 0
542 Synchronization decorator.
544 >>> validate_decorator(call_trace)
549 Entering a((1, 2), {'c': 3})
550 Exiting a((1, 2), {'c': 3})
554 def verboseTrace(*args, **kw):
555 global callTraceIndentationLevel
557 print "%sEntering %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
558 callTraceIndentationLevel += 1
560 result = f(*args, **kw)
562 callTraceIndentationLevel -= 1
563 print "%sException %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
565 callTraceIndentationLevel -= 1
566 print "%sExiting %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
570 def smallTrace(*args, **kw):
571 global callTraceIndentationLevel
573 print "%sEntering %s" % ("\t"*callTraceIndentationLevel, f.__name__)
574 callTraceIndentationLevel += 1
576 result = f(*args, **kw)
578 callTraceIndentationLevel -= 1
579 print "%sException %s" % ("\t"*callTraceIndentationLevel, f.__name__)
581 callTraceIndentationLevel -= 1
582 print "%sExiting %s" % ("\t"*callTraceIndentationLevel, f.__name__)
589 @contextlib.contextmanager
590 def lexical_scope(*args):
592 @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/520586
595 >>> with lexical_scope(1) as (a):
599 >>> with lexical_scope(1,2,3) as (a,b,c):
603 >>> with lexical_scope():
612 frame = inspect.currentframe().f_back.f_back
613 saved = frame.f_locals.keys()
622 f_locals = frame.f_locals
623 for key in (x for x in f_locals.keys() if x not in saved):