Home > Blockchain >  decorate a python class method with another class
decorate a python class method with another class

Time:11-16

I am currently working on a Python class, used as a decorator for a class method. In this context I encountered an issue that I struggle to understand. Let's take the following example:

from functools import partial

class Decorator:
    def __init__(self, func = None, *args):
        self.uses_init = func is None
        self.func = func
        self.instance = None
        self.args = args
    
    def __call__(self, *args, **kwargs):
        self.func = args[0]
        
        def wrapper(cls, *args, **kwargs):
            print('before')
            parsed_func = self.func(cls, *args, **kwargs)
            print('after')
            return parsed_func
        
        return wrapper
    
    def call(self, cls, *args, **kwargs):
        print('before')
        parsed_func = self.func(cls, *args, **kwargs)
        print('after')
        return parsed_func       

    def __get__(self, instance, owner):
        # This is only used when uses_init == False
        return partial(self.call, instance)

which can be used without arguments @Decorator or with arguments @Decorator(*args)

Using this code works as expected:

class HelloWorld:
    @Decorator()
    def print(self, name):
        print(name)
hello_world = HelloWorld()
hello_world.print("Max Musterman")
print('----------------------')
class HelloWorld:
    @Decorator
    def print(self, name):
        print(name)
hello_world = HelloWorld()
hello_world.print("Max Musterman")

I would like to use the self.call method inplace of the wrapper to avoid duplicate code. When I try this:

class Decorator:
    def __init__(self, func = None, *args):
        self.uses_init = func is None
        self.func = func
        self.instance = None
        self.args = args
    
    def __call__(self, *args, **kwargs):
        self.func = args[0]        
        return self.call
    
    def call(self, cls, *args, **kwargs):
        print('before')
        parsed_func = self.func(cls, *args, **kwargs)
        print('after')
        return parsed_func       

    def __get__(self, instance, owner):
        # This is only used when uses_init == False
        return partial(self.call, instance)

I encounter a TypeError: print() missing 1 required positional argument: 'name' despite checking the signature of the methods inspect.signature(Decorator().call) and inspect.signature(Decorator()(lambda: None)) gives identical results.

CodePudding user response:

a decorator cant get argument(s).

>>> class MyClass:
...     def __init__(self, func, *args):
...         print(args)
...
>>> @MyClass
... def my_func():
...     pass
... 
()
>>> @MyClass('args1', 'args2', 'args3')
... def my_func():
...     pass
... 
('args2', 'args3')
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: MyClass object is not callable
>>>

you can use a function or method to make a decorator.
before it "How to solve TypeError: MyClass object is not callable?":

>>> def my_decorator(*args **kwargs):
...     def func_getter(func):
...         return func(*args, **kwargs)
...     return func_getter  # mine decorator
... 
>>> @my_decorator('arg1', 'arg2', 'arg3', kwarg1=1, kwarg2=2) # -> func_getter
... def print_row(*args, **kwargs):
...     print(args, kwargs)
... 
('arg1', 'arg2', 'arg3') {'kwarg1': 1, 'kwarg2': 2}

Solution number 1: Use a function to make a decorator:

>>> class MyClass:
...     def __init__(self, func = None, *args): # copied form your code
...         ... # your code here
... 
>>> def decorator(*args):
...     def func_getter(func):
...         return MyClass(func, *args)
...     return func_getter
... 
>>> @decorator
... def test(): ...
... 
>>> test
<MyClass object at 0x0000000000000000>

Solution number 1: Use a method to make a decorator:

>>> class MyClass:
...     def __init__(self, func = None, *args): # copied form your code
...         ... # your code here
...     @classmethod # romove this line in python3.10
...     def create(cls, *args):
...         def func_getter(func):
...             return cls(func, *args) # "cls" is "MyClass" instance
... 
>>> @MyClass.create('args1', 'arg2', ...)
... def test(): ...
... 
>>> test
<MyClass object at 0x0000000000000000>

CodePudding user response:

Thanks to the answer by @Delta I was able to write a decorator(-maker) that does what I was looking for

class Decorator:
    def __init__(self, func = None, text_before = "start", text_after = "end"):
        self.func = func
        self.text_before = text_before
        self.text_after = text_after
    
    def __call__(self, func):
        return self.create(func, text_before=self.text_before, text_after=self.text_after)
    
    @classmethod
    def create(cls, func, *args, **kwargs):
        return cls(func, *args, **kwargs)
    
    def call(self, cls, *args, **kwargs):
        print(f'--- {self.text_before} ---')
        parsed_func = self.func(cls, *args, **kwargs)
        print(f'--- {self.text_after} ---')
        return parsed_func       

    def __get__(self, instance, owner):
        return partial(self.call, instance)
  • Related