views:

542

answers:

3

I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?

+11  A: 

With:

decorator(original_function)()

Without:

original_function()

A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some documentation might help clarify things.

Ali A
+1  A: 
def original_function():
    pass

decorated_function= decorator(original_function)

if use_decorated:
    decorated_function()
else:
    original_function()

Decorate only once, and afterwards choose which version to call.

ΤΖΩΤΖΙΟΥ
+1  A: 

Here is the recipe I came up with for the problem. I also needed to keep the signatures the same so I used the decorator module but you could re-jig to avoid that. Basically, the trick was to add an attribute to the function. The 'original' function is unbound so you need to pass in a 'self' as the first parameter so I added some extra code to check for that too.

# http://www.phyast.pitt.edu/~micheles/python/decorator-2.0.1.zip
from decorator import decorator, update_wrapper

class mustbe : pass

def wrapper ( interface_ ) :
    print "inside hhh"
    def call ( func, self, *args, **kwargs ) :
        print "decorated"
        print "calling %s.%s with args %s, %s" % (self, func.__name__, args, kwargs)
        return interface_ ( self, *args, **kwargs )
    def original ( instance , *args, **kwargs ) :
        if not isinstance ( instance, mustbe ) :
            raise TypeError, "Only use this decorator on children of mustbe"
        return interface_ ( instance, *args, **kwargs )
    call = decorator ( call, interface_ )
    call.original = update_wrapper ( original, call )
    return call

class CCC ( mustbe ):
    var = "class var"
    @wrapper
    def foo ( self, param ) :
        """foo"""
        print self.var, param

class SSS ( CCC ) :
  @wrapper ( hidden_=True )
  def bar ( self, a, b, c ) :
    print a, b, c

if __name__ == "__main__" :
    from inspect import getargspec

    print ">>> i=CCC()"
    i=CCC()

    print ">>> i.var = 'parrot'"
    i.var = 'parrot'

    print ">>> i.foo.__doc__"
    print i.foo.__doc__

    print ">>> getargspec(i.foo)"
    print getargspec(i.foo)

    print ">>> i.foo(99)"
    i.foo(99)

    print ">>> i.foo.original.__doc__"
    print i.foo.original.__doc__

    print ">>> getargspec(i.foo.original)"
    print getargspec(i.foo.original)

    print ">>> i.foo.original(i,42)"
    i.foo.original(i,42)

    print ">>> j=SSS()"
    j=SSS()

    print ">>> j.bar(1,2,3)"
    j.bar(1,2,3)