2012-03-14 8 views
10

関数の出力をHTMLとして返すデコレータでラップする関数があります。私はデコレータのHTMLラッピングなしでその関数を呼びたいと思います。それも可能ですか?Pythonデコレータをスキップまたは無視する方法

例:応答を待っている間に

class a: 
    @HTMLwrapper 
    def returnStuff(input): 
     return awesome_dict 

    def callStuff(): 
     # here I want to call returnStuff without the @HTMLwrapper, 
     # i just want the awesome dict. 

答えて

4
class a: 
    @HTMLwrapper 
    def return_stuff_as_html(self, input): 
     return self.return_stuff(input) 
    def return_stuff(self, input): 
     return awesome_dict 

は、私は同じことをしたし、それは私のために正常に動作しますが、私はまだ、より良い方法がありますかどうかを知りたいのです: ) - olofom

デコレータが呼び出し可能なものを返すので、関数とメソッドがオブジェクトであるため、デコレータが元のmethを指す装飾されたメソッドに属性を設定できるodですが、my_object_instance.decorated_method.original_method()のような呼び出しは、あいまいであまり明示的ではありません。

>>> import this 
The Zen of Python, by Tim Peters 

Beautiful is better than ugly. 
Explicit is better than implicit. 
Simple is better than complex. 
Complex is better than complicated. 
Flat is better than nested. 
Sparse is better than dense. 
Readability counts. 
Special cases aren't special enough to break the rules. 
Although practicality beats purity. 
Errors should never pass silently. 
Unless explicitly silenced. 
In the face of ambiguity, refuse the temptation to guess. 
There should be one-- and preferably only one --obvious way to do it. 
Although that way may not be obvious at first unless you're Dutch. 
Now is better than never. 
Although never is often better than *right* now. 
If the implementation is hard to explain, it's a bad idea. 
If the implementation is easy to explain, it may be a good idea. 
Namespaces are one honking great idea -- let's do more of those! 
+0

私は待っている間に、ほぼ同じことをしたが、私はちょうどreturnStuffHelperにreturnStuffと改名し、returnStuffを飾ると、その後の呼び出しので、私は、元の関数を変更することが許されませんでした私の関数では代わりにreturnStuffHelper。他のコードでは、HTMLを返すためにreturnStuffが必要です。 – olofom

+0

@olofom:updated –

+0

私はデコレータまたは元のメソッドを変更することはできませんので、それは私にとってはこれよりも良くないと思います。ありがとう:) – olofom

0

確か:

class Example(object): 
    def _implementation(self): 
     return something_awesome() 

    returnStuff = HTMLwrapper(_implementation) 

    def callStuff(self): 
     do_something_with(self._implementation()) 
+0

デコレーションされた機能を変更することはできません。他のコードは依存しています。私はPaulo Scardineのコードを代わりに使いました。 – olofom

2
__author__ = 'Jakob' 

class OptionalDecoratorDecorator(object): 
    def __init__(self, decorator): 
     self.deco = decorator 

    def __call__(self, func): 
     self.deco = self.deco(func) 
     self.func = func 
     def wrapped(*args, **kwargs): 
      if kwargs.get("no_deco") is True: 
       return self.func() 
      else: 
       return self.deco() 
     return wrapped 

def spammer(func): 
    def wrapped(): 
     print "spam" 
     return func() 
    return wrapped 

@OptionalDecoratorDecorator(spammer) 
def test(): 
    print "foo" 

test() 
print "***" 
test(no_deco=True) 
+0

いい例、私の小さなスニペットライブラリに入っています。 – ohmi

+0

:D YAY私はそれらのモジュールにいることが大好きです。 –

+0

これは素晴らしいことです。非常に役立つスニペット。 – krishnab

関連する問題