pythonでアスペクト指向メモ

pythonアスペクト指向プログラミングするために、いろいろライブラリがあるみたい。
適当に目についたのを試してみる。

aspyct

from Aspyct.aop import *

class MyAspect(Aspect):
    def atCall(self, cd):
        print 'called with args', cd.args
        
    def atReturn(self, cd):
        print 'catched return value:', cd.returned

@MyAspect()
def inc(x):
    return x + 1

print inc(10)

・実行結果

called with args (10,)
catched return value: 11
11

Aspectを継承したクラスにatCall/atRetrun/atRiseメソッドを定義する。それぞれ関数が呼ばれる前/呼ばれた後/例外が起こった後がジョインポイントになっている。
このクラスで関数をデコレートする。

python-aspects

import aspects

def wrap(*args, **kwargs):
    print 'called with args', args
    ret = yield aspects.proceed(*args, **kwargs)
    print 'catched return value:', ret
    yield aspects.return_stop(ret)

def inc(x):
    return x + 1

aspects.with_wrap(wrap, inc)
print inc(10)

aspects.proceedでラップされた関数の実行、aspects.return_stop(x)で指定された引数をラップされた関数の戻り値として返す。
実行結果は一緒。


参考:Strategies for aspect oriented programming in Python(pdf)