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

What I would like to do is:

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

But it does not work, because it seems that the first argument is implicitly the actual object of the class. Can I get around this, or am I forced to use an ugly syntax as opposed to this beautiful syntax?

+3
source share
2 answers

The definition arg_cacheshould be 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 that you just want to set some properties in the decorated class. Of course, you could do something else with three parameters.

+5
source

Write a caller that returns the corresponding decorator.

+4
source

Source: https://habr.com/ru/post/1776598/


All Articles