Introduction¶
aspectlib provides two core tools to doAOP: Aspects anda weaver.
The aspect¶
Anaspect can be created by decorating a generator with anAspect. The generator yieldsadvices -simple behavior changing instructions.
AnAspect instance is a simple function decorator. Decorating a function with anaspect will changethe function’s behavior according to theadvices yielded by the generator.
Example:
@aspectlib.Aspectdefstrip_return_value(*args,**kwargs):result=yieldaspectlib.Proceedyieldaspectlib.Return(result.strip())@strip_return_valuedefread(name):returnopen(name).read()
Advices¶
You can use theseadvices:
ProceedorNone- Calls the wrapped function with the default arguments. Theyield returnsthe function’s return value or raises an exception. Can be used multiple times (will call the functionmultiple times).Proceed(*args,**kwargs)- Same as above but with different arguments.Return- Makes the wrapper returnNoneinstead. Ifaspectlib.Proceedwas never used thenthe wrapped function is not called. After this the generator is closed.Return(value)- Same as above but returns the givenvalueinstead ofNone.raiseexception- Makes the wrapper raise an exception.
The weaver¶
Patches classes and functions with the givenaspect. When used with a class it will patch all the methods. In AOPparlance these patched functions and methods are referred to ascut-points.
Returns aRollback object that can be used a context manager.It will undo all the changes at the end of the context.
Example:
@aspectlib.Aspectdefmock_open():yieldaspectlib.Return(StringIO("mystuff"))withaspectlib.weave(open,mock_open):assertopen("/doesnt/exist.txt").read()=="mystuff"
You can useaspectlib.weave() on: classes, instances, builtin functions, module level functions, methods,classmethods, staticmethods, instance methods etc.
