Pastie now auto-senses if line-wrap is a bad or good idea. Feedback?
## mark a section (Learn more)
## a decorating helper class that allows for optional paramaters class ParamDecorator(object): def __init__(self, decorator_function): self.func = decorator_function def __call__(self, *args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # we're being called without paramaters # (just the decorated function) return self.func(args[0]) return self.decorate_with(args, kwargs) def decorate_with(self, args, kwargs): def decorator(callable_): return self.func(callable_, *args, **kwargs) return decorator ## that's the implementation - here are a couple of examples: @ParamDecorator def pending(decorated, reason='no reason given'): def run(*args, **kwargs): print "function '%s' is pending (%s)" % (decorated.__name__, reason) return run @ParamDecorator def trace(decorated, label=None): if label is None: label = decorated.__name__ else: label = "%s (%s)" % (decorated.__name__, label) def run(*args, **kwargs): print "%s: started (args=%s, kwargs=%s)" % (label, args, kwargs) ret = decorated(*args, **kwargs) print "%s: returning: %s" % (label, ret) return ret return run @pending def a(): pass @trace def foo(): return "blah" # NOTE: pastie gets confused by a decorator with args, and seems to show these examples with double "@" symbols. They should only have one. @pending("I haven't done it yet!") def b(): pass @trace("important function") def bar(): return "blech!" if __name__ == '__main__': a() b() foo() bar() ## outputs: # function 'a' is pending (no reason given) # function 'b' is pending (I haven't done it yet!) # foo: started (args=(), kwargs={}) # foo: returning: blah # bar (important function): started (args=(), kwargs={}) # bar (important function): returning: blech!
This paste will be private.
From the Design Piracy series on my blog: