Reference:aspectlib

Overview

Safe toolkit for writing decorators (hereby calledaspects)
aspectlib.AspectContainer for the advice yielding generator.
aspectlib.ProceedInstruction for calling the decorated function.
aspectlib.ReturnInstruction for returning aoptional value.
Power tools for patching functions (hereby glorified asweaving)
aspectlib.ALL_METHODSCompiled regular expression objects
aspectlib.NORMAL_METHODSCompiled regular expression objects
aspectlib.weaveSend a message to a recipient
aspectlib.RollbackWhen called, rollbacks all the patches and changes theweave() has done.

Reference

classaspectlib.Proceed(*args,**kwargs)[source]

Instruction for calling the decorated function. Can be used multiple times.

If not used as an instance then the default args and kwargs are used.

classaspectlib.Return(value)[source]

Instruction for returning aoptional value.

If not used as an instance thenNone is returned.

classaspectlib.Aspect(advising_function,bind=False)[source]

Container for the advice yielding generator. Can be used as a decorator on other function to change behavioraccording to the advices yielded from the generator.

Parameters:
  • advising_function (generator function) – A generator function that yieldsAdvices.
  • bind (bool) – A convenience flag so you can access the cutpoint function (you’ll get it as an argument).

Usage:

>>>@Aspect...defmy_decorator(*args,**kwargs):...print("Got called with args:%s kwargs:%s"%(args,kwargs))...result=yield...print(" ... and the result is:%s"%(result,))>>>@my_decorator...deffoo(a,b,c=1):...print((a,b,c))>>>foo(1,2,c=3)Got called with args: (1, 2) kwargs: {'c': 3}(1, 2, 3) ... and the result is: None

Normally you don’t have access to the cutpoints (the functions you’re going to use the aspect/decorator on) becauseyou don’t and should not call them directly. There are situations where you’d want to get the name or other datafrom the function. This is where you use thebind=True option:

>>>@Aspect(bind=True)...defmy_decorator(cutpoint,*args,**kwargs):...print("`%s` got called with args:%s kwargs:%s"%(cutpoint.__name__,args,kwargs))...result=yield...print(" ... and the result is:%s"%(result,))>>>@my_decorator...deffoo(a,b,c=1):...print((a,b,c))>>>foo(1,2,c=3)`foo` got called with args: (1, 2) kwargs: {'c': 3}(1, 2, 3) ... and the result is: None

You can use theseadvices:

  • Proceed orNone - 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 returnNone instead. Ifaspectlib.Proceed was never used thenthe wrapped function is not called. After this the generator is closed.
  • Return(value) - Same as above but returns the givenvalue instead ofNone.
  • raiseexception - Makes the wrapper raise an exception.

Note

The Aspect will correctly handle generators and coroutines (consume them, capture result).

Example:

>>>fromaspectlibimportAspect>>>@Aspect...deflog_errors(*args,**kwargs):...try:...yield...exceptExceptionasexc:...print("Raised%r for%s/%s"%(exc,args,kwargs))...raise

Will work as expected with generators (and coroutines):

>>>@log_errors...defbroken_generator():...yield1...raiseRuntimeError()>>>frompytestimportraises>>>raises(RuntimeError,lambda:list(broken_generator()))Raised RuntimeError() for ()/{}...>>>@log_errors...defbroken_function():...raiseRuntimeError()>>>raises(RuntimeError,broken_function)Raised RuntimeError() for ()/{}...

And it will handle results:

>>>fromaspectlibimportAspect>>>@Aspect...deflog_results(*args,**kwargs):...try:...value=yield...exceptExceptionasexc:...print("Raised%r for%s/%s"%(exc,args,kwargs))...raise...else:...print("Returned%r for%s/%s"%(value,args,kwargs))>>>@log_results...defweird_function():...yield1...raiseStopIteration('foobar')# in Python 3 it's the same as: return 'foobar'>>>list(weird_function())Returned 'foobar' for ()/{}[1]
classaspectlib.Rollback(rollback=None)[source]

When called, rollbacks all the patches and changes theweave() has done.

__enter__()[source]

Returns self.

__exit__(*_)[source]

Performs the rollback.

rollback(*_)

Alias of__exit__.

__call__(*_)

Alias of__exit__.

aspectlib.ALL_METHODS Weave all magic methods. Can be used as the value for methods argument in weave.

Compiled regular expression objects

aspectlib.NORMAL_METHODS Only weave non-magic methods. Can be used as the value for methods argument in weave.

Compiled regular expression objects

aspectlib.weave(target,aspect[,subclasses=True,methods=NORMAL_METHODS,lazy=False,aliases=True])[source]

Send a message to a recipient

Parameters:
  • target (string, class, instance, function or builtin) – The object to weave.
  • aspects (aspectlib.Aspect, function decorator or list of) – The aspects to apply to the object.
  • subclasses (bool) – IfTrue, subclasses of target are weaved.Only available for classes
  • aliases (bool) – IfTrue, aliases of target are replaced.
  • lazy (bool) – IfTrue only target’s__init__ method is patched, the rest of the methods are patched after__init__ is called.Only available for classes.
  • methods (list or regex or string) – Methods from target to patch.Only available for classes
Returns:

aspectlib.Rollback – An object that can rollback the patches.

Raises:

TypeError – If target is a unacceptable object, or the specified options are not available for that type ofobject.

Changed in version 0.4.0:Replacedonly_methods,skip_methods,skip_magicmethods options withmethods.Renamedon_init option tolazy.Addedaliases option.Replacedskip_subclasses option withsubclasses.