複数のデコレータをひとつにまとめる
複数のデコレータをひとつの関数に付与するのが、何度も続くと面倒くさい。
@decorator1 @decorator2 @decorator3 def f(): pass
ひとつのデコレータにまとめてみても良いかも。
# -*- coding:utf-8 -*- def decorator_compose(*decorators): def _decorator_compose(target_func): for d in reversed(decorators): target_func = d(target_func) return target_func return _decorator_compose def inc(fn): def _inc(x): return fn(x+1) return _inc def twice(fn): def _twice(x): return fn(x*2) return _twice def dec(fn): def _dec(x): return fn(x-1) return _dec @inc @twice @dec def f(x): return x ## twice_plus1 = decorator_compose(inc, twice, dec) @twice_plus1 def g(x): return x import nose def test_f_and_g_results_are_same(): assert f(10) == g(10) == 21 nose.main() # print f(10) g(10) # print g(10)