0

Do python decorator function support arguments a how is the implementation

def decorator(fn, decorArg):
    print "I'm decorating!"
    print decorArg
    return fn

class MyClass(object):
    def __init__(self):
        self.list = []

    @decorator
    def my_function(self, funcArg = None):
        print "Hi"
        print funcArg

on run I got this error

TypeError: decorator() takes exactly 2 arguments (1 given)

I've tried @decorator(arg) or @ decorator arg . it did not work as well. So far I wonder if this is possible

Cobry
  • 4,348
  • 8
  • 33
  • 49
  • 1
    Yes, but your example seems to indicate that you don't understand how decorators work. Have you read, for instance, [this](http://www.python.org/dev/peps/pep-0318/#current-syntax)? What do you want your decorator to do? – BrenBarn Mar 02 '13 at 06:36
  • 1
    You should read this post order to better understand how to use decorators: http://stackoverflow.com/questions/739654/understanding-python-decorators – Carlos Mar 02 '13 at 06:41

1 Answers1

3

I think you might want something like this:

class decorator:
    def __init__ (self, decorArg):
        self.arg = decorArg

    def __call__ (self, fn):
        print "I'm decoratin!"
        print self.arg
        return fn

class MyClass (object):
    def __init__ (self):
        self.list = []

    @decorator ("foo")
    def my_function (self, funcArg = None):
        print "Hi"
        print funcArg

MyClass ().my_function ("bar")

Or with nested functions as BlackNight pointed out:

def decorator (decorArg):
    def f (fn):
        print "I'm decoratin!"
        print decorArg
        return fn
    return f
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • You can also do it with nested functions, rather than a decorator class. Alas, Python's indentation requirements don't let me type an example here in the comments. – Blckknght Mar 02 '13 at 07:14