我们可以从这样的基础开始:
from functools import partial, update_wrapper
class Decorator:
"""A transparent decorator -- to be subclassed"""
def __new__(cls, func=None, **kwargs):
if func is None:
return partial(cls, **kwargs)
else:
self = super().__new__(cls)
self.func = func
for attr_name, attr_val in kwargs.items():
setattr(self, attr_name, attr_val)
return update_wrapper(self, func)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
它允许通过子类化和定义__new__
方法(应该调用其父方法)来定义装饰器工厂。
然后,可以使用直接从子类的属性中__init_subclass__
提取所需的参数__new__
,如下所示:
from inspect import Signature, Parameter
PK, KO = Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY
class Literal:
"""An object to indicate that the value should be considered literally"""
def __init__(self, val):
self.val = val
class Decora(Decorator):
_injected_deco_params = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if '__new__' not in cls.__dict__: # if __new__ hasn't been defined in the subclass...
params = ([Parameter('self', PK), Parameter('func', PK, default=None)])
cls_annots = getattr(cls, '__annotations__', {})
injected_deco_params = set()
for attr_name in (a for a in cls.__dict__ if not a.startswith('__')):
attr_obj = cls.__dict__[attr_name] # get the attribute
if not isinstance(attr_obj, Literal):
setattr(cls, attr_name, attr_obj) # what we would have done anyway...
# ... but also add a parameter to the list of params
params.append(Parameter(attr_name, KO, default=attr_obj,
annotation=cls_annots.get(attr_name, Parameter.empty)))
injected_deco_params.add(attr_name)
else: # it is a Literal, so
setattr(cls, attr_name, attr_obj.val) # just assign the literal value
cls._injected_deco_params = injected_deco_params
def __new__(cls, func=None, **kwargs):
if cls._injected_deco_params and not set(kwargs).issubset(cls._injected_deco_params):
raise TypeError("TypeError: __new__() got unexpected keyword arguments: "
f"{kwargs.keys() - cls._injected_deco_params}")
if func is None:
return partial(cls, **kwargs)
else:
return Decorator.__new__(cls, func, **kwargs)
__new__.__signature__ = Signature(params)
cls.__new__ = __new__
它通过了问题中列出的测试,但我对这种面向对象的魔法并不是很有经验,所以很想看到替代解决方案。