by brian_herman · 8y ago · 0 comments
@decorator_with_params("Some string")
def my_function():
pass
you have to make 'decorator_with_params' a function that returns a decorator; i.e. def decorator_with_params(param):
def real_decorator(function):
def inner(*args, **kwargs):
print(param)
function(*args, **kwargs)
return inner
return real_decorator
(You can also do something similar with callable objects, but that's ickier IMO.)Demo of both (decorator as instance method and decorator with parameters): https://gist.github.com/jonathonw/dac88b715aca4e4f1b2f513e1f...
class MetaDec(args, here):
...
def __call__(self, func):
# Decorate function here
def meta_dec(args, here):
return MetaDec(args, here)
@meta_dec
def decorated:
...
(apologies for any syntax fails, python is not my best language)At which point one would imagine you can abstract out the __call__ part and just have a 'decorate' routine on any class designed to work what way or similar.
Whether this is an improvement or not over closures almost certainly depends on the use case, of course.
class FancyDecorator():
__init__(self, *args):
self.args = args
__call__(self, fn):
return decorate_fn_with_args(fn, self.args)
dec = FancyDecorator(42)
@dec
def foo():
pass
@FancyDecorator(41)
def bar()
pass
Might have it wrong since I haven't messed with decorators in a while and they aren't exactly what one would call simple.--edit--
code formatting is all wonky so...