Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a Python class decorator with arguments?

What I'd like to do is this:

@add_cache(cache_this, cache_that, cache_this_and_that)
class MyDjangoModel(models.Model):
    blah

But fails because it seems that the first argument is implicitly the actual class object. Is it possible to get around this or am I forced to use the ugly syntax as opposed to this beautiful syntax?

like image 225
guidoism Avatar asked Nov 24 '10 02:11

guidoism


2 Answers

Your arg_cache definition needs to do something like:

def arg_cache(cthis, cthat, cthisandthat):
   def f(obj):
       obj.cache_this = cthis
       obj.cache_that = cthat
       obj.thisandthat = cthisandthat
       return obj
   return f

@arg_cache(cache_this, cache_that, cache_this_and_that)
...

The example assumes you just want to set some properties on the decorated class. You could of course do something else with the three parameters.

like image 81
Edmund Avatar answered Oct 21 '22 20:10

Edmund


Write a callable that returns an appropriate decorator.

like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 20:10

Ignacio Vazquez-Abrams