guidoism
guidoism

Reputation: 8158

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?

Upvotes: 6

Views: 4345

Answers (2)

Edmund
Edmund

Reputation: 10819

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.

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

Write a callable that returns an appropriate decorator.

Upvotes: 1

Related Questions