実行時に関数/メソッドデコレータを置き換えることは可能ですか? [python]

StackOverflow https://stackoverflow.com/questions/642762

質問

機能がある場合:


@aDecorator
def myfunc1():
  # do something here

if __name__ = "__main__":
  # this will call the function and will use the decorator @aDecorator
  myfunc1() 
  # now I want the @aDecorator to be replaced with the decorator @otherDecorator
  # so that when this code executes, the function no longer goes through
  # @aDecorator, but instead through @otherDecorator. How can I do this?
  myfunc1()

実行時にデコレータを置き換えることは可能ですか?

役に立ちましたか?

解決

「置換」する方法があるかどうかわからない一度適用されたデコレータですが、おそらく機能は変更されているので、おそらくないでしょう。

とにかく、いくつかの条件に基づいて実行時にデコレータを適用できます:

#!/usr/bin/env python

class PrintCallInfo:
    def __init__(self,f):
        self.f = f
    def __call__(self,*args,**kwargs):
        print "-->",self.f.__name__,args,kwargs
        r = self.f(*args,**kwargs)
        print "<--",self.f.__name__,"returned: ",r
        return r

# the condition to modify the function...
some_condition=True

def my_decorator(f):
    if (some_condition): # modify the function
        return PrintCallInfo(f)
    else: # leave it as it is
        return f

@my_decorator
def foo():
    print "foo"

@my_decorator
def bar(s):
    print "hello",s
    return s

@my_decorator
def foobar(x=1,y=2):
    print x,y
    return x + y

foo()
bar("world")
foobar(y=5)

他のヒント

Miyaが述べたように、インタープリターがその関数宣言に到達する前であれば、デコレーターを別の関数に置き換えることができます。ただし、デコレータが関数に適用されると、デコレータを別のデコレータに動的に置き換える方法はないと思います。例えば:

@aDecorator
def myfunc1():
    pass

# Oops! I didn't want that decorator after all!

myfunc1 = bDecorator(myfunc1)

myfunc1は最初に定義した関数ではなくなったため、機能しません。既にラップされています。ここでの最良のアプローチは、oldskoolスタイルのデコレータを手動で適用することです:

def myfunc1():
    pass

myfunc2 = aDecorator(myfunc1)
myfunc3 = bDecorator(myfunc1)

編集:または、より明確にするために、

def _tempFunc():
    pass

myfunc1 = aDecorator(_tempFunc)
myfunc1()
myfunc1 = bDecorator(_tempFunc)
myfunc1()

これは素晴らしい始めるためのレシピです。基本的に、アイデアはクラスインスタンスをデコレータに渡すことです。次に、クラスインスタンスに属性を設定し(必要に応じてBorgにできます)、それを使用してデコレータ自体の動作を制御できます。

例を次に示します。

class Foo:
    def __init__(self, do_apply):
        self.do_apply = do_apply

def dec(foo):
    def wrap(f):
        def func(*args, **kwargs):
            if foo.do_apply:
                # Do something!
                pass 
            return f(*args, **kwargs)
        return func
    return wrap

foo = Foo(False)
@dec(foo)
def bar(x):
    return x

bar('bar') 
foo.do_apply = True 
# Decorator now active!
bar('baz')

当然、「デコレータデコレータ」も組み込むことができます。署名などを保持します。

もちろん-関数オブジェクトを取得して、それを使って何でもできます:

# Bypass a decorator

import types

class decorator_test(object):

    def __init__(self, f):
        self.f = f

    def __call__(self):
        print "In decorator ... entering: ", self.f.__name__
        self.f()
        print "In decorator ... exiting: ", self.f.__name__


@decorator_test
def func1():
    print "inside func1()"

print "\nCalling func1 with decorator..."
func1()

print "\nBypassing decorator..."
for value in func1.__dict__.values():
    if isinstance(value, types.FunctionType) and value.func_name == "func1":
        value.__call__()

デコレータを明示的に変更する場合は、装飾された関数を作成する代わりに、より明示的なアプローチを選択することもできます。

deco1(myfunc1, arg1, arg2)
deco2(myfunc1, arg2, arg3)

deco1()およびdeco2()は、デコレータが提供する機能を適用し、引数でmyfunc1()を呼び出します。

古いスレッドであることは知っていますが、これを楽しんでいます

def change_deco(name, deco, placeholder='    #'):
with open(name + '.py', 'r') as file:
    lines = file.readlines()
for idx, string in enumerate(lines):
    if placeholder in string and repr(placeholder) not in string:
        lines[idx] = f'    @{deco}\r\n'
exec(''.join(lines))
return locals()[name]

デコレータが関数である場合、それを置き換えるだけです。

aDecorator = otherDecorator
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top