How to create a decorator function with python class arguments?

I want to create a decorator function to work with a python class with the ability to pass additional arguments. I want to do this before the class is created. Here is my approach:

def register(x,a): print x,a @register(5) class Foo(object): pass 

with x is a class and a an optional argument. But I get

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

I want to somehow get the Foo class and additional arguments at the time the class is defined before the class instance is created.

+4
source share
1 answer

You need to do it like this:

 def makeDeco(a): def deco(cls): print cls, a return cls return deco >>> @makeDeco(3) ... class Foo(object): ... pass <class '__main__.Foo'> 3 

You can use functools.wraps etc. to decorate it, but this is an idea. You need to write a function that returns a decorator. The external function of "creating a decorator" accepts the argument a , and the function of the internal decorator accepts a class.

How it works, when you write @makeDeco(3) , it calls makeDeco(3) . The return value of makeDeco is what is used as a decorator. This is why you need makeDeco to return the function you want to use as a decorator.

+6
source

All Articles