@decorator2で装飾されている特定のクラスAのすべてのメソッドを取得するにはどうすればよいですか?
class A():
def method_a(self):
pass
@decorator1
def method_b(self, b):
pass
@decorator2
def method_c(self, t=5):
pass
私はすでにここでこの質問に答えました:Pythonの配列インデックスによる関数の呼び出し=)
想定したいものの1つの解釈であるクラス定義を制御できない場合、これは不可能です(コード読み取り-リフレクションなし)。たとえば、デコレータは操作なしのデコレータである可能性があります(リンクされた例では、関数を変更せずに返すだけです。(それでも、デコレータをラップ/再定義できるようにする場合は、方法3:デコレータを「自己認識」に変換するを参照してください。そうすれば、エレガントな解決策が見つかります)
これはひどいひどいハックですが、inspect
モジュールを使用してソースコード自体を読み取り、解析することができます。inspectモジュールはインタラクティブモードでソースコードを提供することを拒否するため、これはインタラクティブインタプリタでは機能しません。ただし、以下は概念実証です。
#!/usr/bin/python3
import inspect
def deco(func):
return func
def deco2():
def wrapper(func):
pass
return wrapper
class Test(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
for i,line in enumerate(sourcelines):
line = line.strip()
if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
nextLine = sourcelines[i+1]
name = nextLine.split('def')[1].split('(')[0].strip()
yield(name)
できます!:
>>> print(list( methodsWithDecorator(Test, 'deco') ))
['method']
解析とPython構文に注意を払う必要があることに注意してください。たとえば@deco
、and@deco(...
は有効な結果ですが、@deco2
単に要求した場合は返されません'deco'
。http://docs.python.org/reference/compound_stmts.htmlの公式Python構文によると、デコレータは次のとおりです。
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
のようなケースに対処する必要がないことに、私たちは安堵のため息をつき@(deco)
ます。@getDecorator(...)
ただし、たとえば、などの非常に複雑なデコレータがある場合、これはまだ実際には役に立ちません。
def getDecorator():
return deco
したがって、コードを解析するこの最善の戦略では、このようなケースを検出することはできません。ただし、このメソッドを使用している場合、実際に求めているのは、定義のメソッドの上に記述されているものです。この場合はgetDecorator
です。
仕様によると@foo1.bar2.baz3(...)
、デコレータとしても有効です。このメソッドを拡張して、それを処理できます。<function object ...>
また、多くの労力を費やして、このメソッドを拡張して、関数の名前ではなく名前を返すことができる場合もあります。ただし、この方法はハック的でひどいものです。
デコレータの定義を制御できない場合(これは、必要なものの別の解釈です)、デコレータの適用方法を制御できるため、これらの問題はすべて解消されます。したがって、デコレータをラップして変更し、独自のデコレータを作成し、それを使用して関数を装飾することができます。もう一度言いましょう。制御できないデコレータを装飾するデコレータを作成して「啓発」することができます。これにより、以前と同じように動作するだけでなく、.decorator
返される呼び出し可能オブジェクトにメタデータプロパティが追加されます。 、「この関数は装飾されているかどうか?function.decoratorを確認しましょう!」を追跡できます。.decorator
クラスのメソッドを繰り返し処理して、デコレータに適切なプロパティがあるかどうかを確認するだけです。=)ここに示されているように:
def makeRegisteringDecorator(foreignDecorator):
"""
Returns a copy of foreignDecorator, which is identical in every
way(*), except also appends a .decorator property to the callable it
spits out.
"""
def newDecorator(func):
# Call to newDecorator(method)
# Exactly like old decorator, but output keeps track of what decorated it
R = foreignDecorator(func) # apply foreignDecorator, like call to foreignDecorator(method) would have done
R.decorator = newDecorator # keep track of decorator
#R.original = func # might as well keep track of everything!
return R
newDecorator.__name__ = foreignDecorator.__name__
newDecorator.__doc__ = foreignDecorator.__doc__
# (*)We can be somewhat "hygienic", but newDecorator still isn't signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries...but in this case, the only argument is func, so it's not a big issue
return newDecorator
のデモンストレーション@decorator
:
deco = makeRegisteringDecorator(deco)
class Test2(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decorator):
"""
Returns all methods in CLS with DECORATOR as the
outermost decorator.
DECORATOR must be a "registering decorator"; one
can make any decorator "registering" via the
makeRegisteringDecorator function.
"""
for maybeDecorated in cls.__dict__.values():
if hasattr(maybeDecorated, 'decorator'):
if maybeDecorated.decorator == decorator:
print(maybeDecorated)
yield maybeDecorated
できます!:
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
ただし、「登録されたデコレータ」は最も外側のデコレータである必要があります。そうでない場合、.decorator
属性の注釈は失われます。たとえば、
@decoOutermost
@deco
@decoInnermost
def func(): ...
decoOutermost
「より内側の」ラッパーへの参照を保持しない限り、公開するメタデータのみを表示できます。
補足:上記のメソッドは、適用されたデコレータと入力関数およびデコレータファクトリ引数のスタック全体.decorator
を追跡するを構築することもできます。=)たとえば、コメント化された行を検討する場合、このような方法を使用してすべてのラッパーレイヤーを追跡することができます。これは、デコレータライブラリを作成した場合に個人的に行うことです。これにより、深い内省が可能になります。R.original = func
との間にも違いが@foo
あり@bar(...)
ます。これらは両方とも仕様で定義されている「デコレータエクスプレッション」ですが、それはデコレータであり、動的に作成されたデコレータfoo
をbar(...)
返し、それが適用されることに注意してください。したがって、別の関数が必要になりますmakeRegisteringDecoratorFactory
。これは、多少似てmakeRegisteringDecorator
いますが、さらにメタです。
def makeRegisteringDecoratorFactory(foreignDecoratorFactory):
def newDecoratorFactory(*args, **kw):
oldGeneratedDecorator = foreignDecoratorFactory(*args, **kw)
def newGeneratedDecorator(func):
modifiedFunc = oldGeneratedDecorator(func)
modifiedFunc.decorator = newDecoratorFactory # keep track of decorator
return modifiedFunc
return newGeneratedDecorator
newDecoratorFactory.__name__ = foreignDecoratorFactory.__name__
newDecoratorFactory.__doc__ = foreignDecoratorFactory.__doc__
return newDecoratorFactory
のデモンストレーション@decorator(...)
:
def deco2():
def simpleDeco(func):
return func
return simpleDeco
deco2 = makeRegisteringDecoratorFactory(deco2)
print(deco2.__name__)
# RESULT: 'deco2'
@deco2()
def f():
pass
このジェネレーターファクトリーラッパーも機能します。
>>> print(f.decorator)
<function deco2 at 0x6a6408>
ボーナス方法#3で次のことも試してみましょう。
def getDecorator(): # let's do some dispatching!
return deco
class Test3(object):
@getDecorator()
def method(self):
pass
@deco2()
def method2(self):
pass
結果:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
ご覧のとおり、method2とは異なり、@ decoは、クラスで明示的に記述されていなくても正しく認識されます。method2とは異なり、これは、メソッドが実行時に(手動で、メタクラスなどを介して)追加された場合、または継承された場合にも機能します。
クラスをデコレートすることもできることに注意してください。メソッドとクラスのデコレーションの両方に使用されるデコレータを「啓発」してから、分析するクラスの本体内にクラスを作成すると、デコレートされたクラスは次のmethodsWithDecorator
ように返されます。装飾された方法と同様に。これは機能と見なすことができますが、デコレータへの引数を調べることで、それらを無視するロジックを簡単に記述できます。つまり.original
、目的のセマンティクスを実現できます。
方法2:ソースコードの解析における@ninjageckoの優れた回答を拡張するにはast
、inspectモジュールがソースコードにアクセスできる限り、Python2.6で導入されたモジュールを使用して自己検査を実行できます。
def findDecorators(target):
import ast, inspect
res = {}
def visit_FunctionDef(node):
res[node.name] = [ast.dump(e) for e in node.decorator_list]
V = ast.NodeVisitor()
V.visit_FunctionDef = visit_FunctionDef
V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
return res
もう少し複雑な装飾方法を追加しました。
@x.y.decorator2
def method_d(self, t=5): pass
結果:
> findDecorators(A)
{'method_a': [],
'method_b': ["Name(id='decorator1', ctx=Load())"],
'method_c': ["Name(id='decorator2', ctx=Load())"],
'method_d': ["Attribute(value=Attribute(value=Name(id='x', ctx=Load()), attr='y', ctx=Load()), attr='decorator2', ctx=Load())"]}
デコレータを制御できる場合は、関数ではなくデコレータクラスを使用できます。
class awesome(object):
def __init__(self, method):
self._method = method
def __call__(self, obj, *args, **kwargs):
return self._method(obj, *args, **kwargs)
@classmethod
def methods(cls, subject):
def g():
for name in dir(subject):
method = getattr(subject, name)
if isinstance(method, awesome):
yield name, method
return {name: method for name,method in g()}
class Robot(object):
@awesome
def think(self):
return 0
@awesome
def walk(self):
return 0
def irritate(self, other):
return 0
そして私がそれを呼ぶならばawesome.methods(Robot)
それは戻る
{'think': <mymodule.awesome object at 0x000000000782EAC8>, 'walk': <mymodulel.awesome object at 0x000000000782EB00>}
可能な限り単純なケース、つまり、作業しているクラスと追跡しようとしているデコレータの両方を完全に制御できる単一ファイルソリューションが必要な場合は、答えが得られます。 。ninjageckoは、追跡したいデコレータを制御できる場合のソリューションにリンクしていますが、個人的には、これまでデコレータを使用したことがないためか、複雑で理解しにくいと感じました。そこで、できるだけ単純でシンプルにすることを目標に、次の例を作成しました。これはデコレータであり、いくつかのデコレートされたメソッドを持つクラスであり、特定のデコレータが適用されているすべてのメソッドを取得して実行するためのコードです。
# our decorator
def cool(func, *args, **kwargs):
def decorated_func(*args, **kwargs):
print("cool pre-function decorator tasks here.")
return_value = func(*args, **kwargs)
print("cool post-function decorator tasks here.")
return return_value
# add is_cool property to function so that we can check for its existence later
decorated_func.is_cool = True
return decorated_func
# our class, in which we will use the decorator
class MyClass:
def __init__(self, name):
self.name = name
# this method isn't decorated with the cool decorator, so it won't show up
# when we retrieve all the cool methods
def do_something_boring(self, task):
print(f"{self.name} does {task}")
@cool
# thanks to *args and **kwargs, the decorator properly passes method parameters
def say_catchphrase(self, *args, catchphrase="I'm so cool you could cook an egg on me.", **kwargs):
print(f"{self.name} says \"{catchphrase}\"")
@cool
# the decorator also properly handles methods with return values
def explode(self, *args, **kwargs):
print(f"{self.name} explodes.")
return 4
def get_all_cool_methods(self):
"""Get all methods decorated with the "cool" decorator.
"""
cool_methods = {name: getattr(self, name)
# get all attributes, including methods, properties, and builtins
for name in dir(self)
# but we only want methods
if callable(getattr(self, name))
# and we don't need builtins
and not name.startswith("__")
# and we only want the cool methods
and hasattr(getattr(self, name), "is_cool")
}
return cool_methods
if __name__ == "__main__":
jeff = MyClass(name="Jeff")
cool_methods = jeff.get_all_cool_methods()
for method_name, cool_method in cool_methods.items():
print(f"{method_name}: {cool_method} ...")
# you can call the decorated methods you retrieved, just like normal,
# but you don't need to reference the actual instance to do so
return_value = cool_method()
print(f"return value = {return_value}\n")
上記の例を実行すると、次の出力が得られます。
explode: <bound method cool.<locals>.decorated_func of <__main__.MyClass object at 0x00000220B3ACD430>> ...
cool pre-function decorator tasks here.
Jeff explodes.
cool post-function decorator tasks here.
return value = 4
say_catchphrase: <bound method cool.<locals>.decorated_func of <__main__.MyClass object at 0x00000220B3ACD430>> ...
cool pre-function decorator tasks here.
Jeff says "I'm so cool you could cook an egg on me."
cool post-function decorator tasks here.
return value = None
この例の装飾されたメソッドには、さまざまなタイプの戻り値とさまざまなシグネチャがあるため、それらすべてを取得して実行できることの実際的な価値は少し疑わしいことに注意してください。ただし、多くの同様のメソッドがあり、すべて同じシグニチャや戻り値のタイプがある場合(たとえば、あるデータベースから正規化されていないデータを取得し、それを正規化して、別のデータベースに挿入するコネクタを作成している場合など)正規化されたデータベースであり、同様のメソッドがたくさんあります(たとえば、15個のread_and_normalize_table_Xメソッド)。これらすべてをオンザフライで取得(および実行)できると、より便利な場合があります。
たぶん、デコレータがそれほど複雑でなければ(しかし、もっとハッキーな方法があるかどうかはわかりません)。
def decorator1(f):
def new_f():
print "Entering decorator1", f.__name__
f()
new_f.__name__ = f.__name__
return new_f
def decorator2(f):
def new_f():
print "Entering decorator2", f.__name__
f()
new_f.__name__ = f.__name__
return new_f
class A():
def method_a(self):
pass
@decorator1
def method_b(self, b):
pass
@decorator2
def method_c(self, t=5):
pass
print A.method_a.im_func.func_code.co_firstlineno
print A.method_b.im_func.func_code.co_firstlineno
print A.method_c.im_func.func_code.co_firstlineno
この問題を解決する簡単な方法は、渡される各関数/メソッドをデータセット(リストなど)に追加するデコレータにコードを配置することです。
例えば
def deco(foo):
functions.append(foo)
return foo
これで、デコデコレータを備えたすべての関数が関数に追加されます。
あまり追加したくありません。ninjageckoの方法2の単純なバリエーションです。驚異的に機能します。
同じコードですが、ジェネレーターの代わりにリスト内包表記を使用しています。これが私が必要としていたものです。
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
return [ sourcelines[i+1].split('def')[1].split('(')[0].strip()
for i, line in enumerate(sourcelines)
if line.split('(')[0].strip() == '@'+decoratorName]