/ / pythonメソッドをオプションの引数で装飾する - python、decorator

オプション引数付きのPythonメソッドをデコレートする - python、decorator

私はシグネチャを持つ多くのメソッドを持つPythonクラスを持っています。

def select_xxx(self, arg1 , arg2 , .. argn, intersect = False)

すなわち メソッドはさまざまな(1〜3)個の位置引数を持ち、オプションの引数はデフォルト値Falseと交差します。インターセクトパラメータの値を無視し、それに応じてさまざまなアクションを実行するデコレータを使用して、これらすべてのメソッドをデコレートします。私の現在のアプローチはこのようなものです。

def select_decorator(select_method):

def select_wrapper( self , *args, intersect = False , **kwargs)
if intersect:
# Special init code for intersect == True
select_method( self , *args , **kwargs)
else:
# Normal call path for intersect == False
select_method( self , *args , **kwargs)

return select_wrapper

@select_decorator
select_xxx( self , arg1 , arg2 , intersect = False)

しかし、オプションの引数を取得することはに交差します* argsと** kwargsがデコレータの中で混在しているのは、現在のところ喜びではありません。それが問題を解決するのをより簡単にするならば、私は** kwargs機能性を犠牲にすることができました。助言がありますか?

ヨアキム

回答:

回答№1は2

交差は常にキーワード引数として渡されると思います。その場合あなたは単にあなたのデコレータの中でこれをすることができます

def select_decorator(select_method):

def select_wrapper( self , *args, **kwargs):
intersect = kwargs.has_key("intersect") and kwargs["intersect"]
if intersect:
# Special init code for intersect == True
select_method( self , *args , **kwargs)
else:
# Normal call path for intersect == False
select_method( self , *args , **kwargs)
return select_wrapper