Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

A lean interface for making python decorator classes

I've been looking to make an object-oriented setup to make decorator factories. A simple version can be found in this stackoverflow answer. But I'm not totally satisfied with the simplicity of the interface.

THe kind of interface I envision would use special class Decora that I can use as such:

class MultResult(Decora):
    mult: int = 1
    i_am_normal = Literal(True)  # will not be included in the __init__

    def __call__(self, *args, **kwargs):  # code for the wrapped functoin
        return super().__call__(*args, **kwargs) * self.mult

That would result in the following behavior:

>>> @MultResult(mult=2)
... def f(x, y=0):
...     return x + y
...
>>>
>>> signature(MultResult)  # The decorator has a proper signature
<Signature (func=None, *, mult: int = 1)>
>>> signature(f)  # The decorated has a proper signature
<Signature (x, y=0)>
>>> f(10)
20
>>>
>>> ff = MultResult(lambda x, y=0: x + y)  # default mult=1 works
>>> assert ff(10) == 10
>>>
>>> @MultResult  # can also use like this
... def fff(x, y=0):
...     return x + y
...
>>> assert fff(10) == 10
>>>
>>> MultResult(any_arg=False)  # should refuse that arg!
Traceback (most recent call last):
...
TypeError: TypeError: __new__() got unexpected keyword arguments: {'any_arg'}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can start with a base such as this:

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)

It allows one to define decorator factories by subclassing and defining a __new__ method (that should call its parent).

Then, one can use __init_subclass__ to extract the desired arguments of that __new__ directly from attributes of the subclass, as such:

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__

It passes the tests listed in the question, but I'm not super experienced with this kind of object oriented magic, so would be curious to see alternative solutions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...