问题
Consider the following decorator function, which either returns a decorated function, or a parametrized decorator function:
from functools import wraps, partial, update_wrapper
from inspect import signature
def wrapit(func=None, *, verb='calling'):
if func is None: # return a decoratOR
return partial(wrapit, verb=verb)
else: # return a decoratED
@wraps(func)
def _func(*args, **kwargs):
print(f'{verb} {func.__name__} with {args} and {kwargs}')
return func(*args, **kwargs)
return _func
Demo:
>>> f = lambda x, y=1: x + y
>>> ff = wrapit(verb='launching')(f)
>>> assert ff(10) == 11
launching <lambda> with (10,) and {}
>>> assert signature(ff) == signature(f)
>>>
>>> # but can also use it as a "decorator factory"
>>> @wrapit(verb='calling')
... def f(x, y=1):
... return x + y
...
>>> assert ff(10) == 11
launching <lambda> with (10,) and {}
>>> assert signature(ff) == signature(f)
The class form could look something like this:
class Wrapit:
def __init__(self, func, verb='calling'):
self.func, self.verb = func, verb
update_wrapper(self, func)
def __call__(self, *args, **kwargs):
print(f'{self.verb} {self.func.__name__} with {args} and {kwargs}')
return self.func(*args, **kwargs)
But how do we get the class to be able to operate in the "decorator factory" mode that the functional form has (implemented by the if func is None: return partial...
How do we integrate that trick in a decorator class?
回答1:
As was suggested in the comments, you can do this using the __new__
method:
class Wrapit:
def __new__(cls, func=None, *, verb='calling'):
if func is None:
return partial(cls,verb=verb)
self = super().__new__(cls)
self.func, self.verb = func, verb
update_wrapper(self, func)
return self
def __call__(self, *args, **kwargs):
print(f'{self.verb} {self.func.__name__} with {args} and {kwargs}')
return self.func(*args, **kwargs)
The __new__
method is called whenever you try to instantiate a class, and the return value of that method is used as the result of the attempted instantiation -- even if it's not an instance of the class!
回答2:
I accepted @pppery's answer because... it was the answer. I wanted to extend the answer here by showing how one can get a bit more reuse by coding the logic in a parent class. This requires one to separate @pppery's logic into the __new__
and __init__
methods.
from functools import update_wrapper, partial
class Decorator:
def __new__(cls, func=None, **kwargs):
if func is None:
self = partial(cls, **kwargs)
else:
self = super().__new__(cls)
return update_wrapper(self, func)
def __init__(self, func=None, **kwargs):
self.func = func
for attr_name, attr_val in kwargs.items():
setattr(self, attr_name, attr_val)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
class Wrapit(Decorator):
def __new__(cls, func=None, *, verb='calling'):
return super().__new__(cls, func, verb=verb)
def __call__(self, *args, **kwargs):
print(f'{self.verb} {self.func.__name__} with {args} and {kwargs}')
return super().__call__(*args, **kwargs)
class AnotherOne(Decorator):
def __new__(cls, func=None, *, postproc=lambda x: x):
return super().__new__(cls, func, postproc=postproc)
def __call__(self, *args, **kwargs):
return self.postproc(super().__call__(*args, **kwargs))
Demo:
>>> f = lambda x, y=1: x + y
>>>
>>> ff = Wrapit(f, verb='launching')
>>> assert ff(10) == 11
launching <lambda> with (10,) and {}
>>> assert signature(ff) == signature(f)
>>>
>>> fff = AnotherOne(postproc=str)(f) # doing it the decorator factory way
>>> assert fff(10) == str(11)
>>> assert signature(fff) == signature(f)
来源:https://stackoverflow.com/questions/62379216/using-a-class-to-operate-both-as-decorator-and-decorator-factory