2012-03-14 15 views
10

Hay una función envuelta por un decorador que devuelve el resultado de la función como HTML. Me gustaría llamar a esa función sin el envoltorio HTML del decorador. ¿Es eso posible?Cómo saltear o ignorar los decoradores de pitón

Ejemplo:

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. 

Respuesta

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

me hicieron lo mismo a la espera de una respuesta y funciona muy bien para mí, pero todavía me gustaría saber si hay una mejor manera:) - olofom

Dado que en python las funciones y los métodos son objetos, y dado que un decorador devuelve un llamador, puede establecer un atributo en el método decorado que apunte a la metanfetamina original od, pero una llamada como my_object_instance.decorated_method.original_method() sería más fea y menos explícita.

>>> 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

lo hice casi la misma cosa mientras espera, pero no se le permitió cambiar la función original así que sólo cambió el nombre returnStuff a returnStuffHelper y decora returnStuff y luego llamadas returnStuffHelper en mi función en su lugar. Otro código necesita el returnStuff para devolver HTML. – olofom

+0

@olofom: actualizado –

+0

No puedo cambiar ni el decorador ni el método original, así que supongo que no será mejor que esto para mí. Gracias :) – olofom

0

Claro:

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

    returnStuff = HTMLwrapper(_implementation) 

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

No tengo permitido cambiar la función decorada, otro código depende de ella. Fui con el código de Paulo Scardine en su lugar. – 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

Buen ejemplo, yendo en mi pequeña biblioteca de fragmentos. – ohmi

+0

: D YAY Me encanta estar en esos módulos. –

+0

Esto es genial. Fragmento muy útil. – krishnab

Cuestiones relacionadas