Grigusky
Grigusky

Reputation: 1

Python: passing an object from the decorator itself

I try to pass class attributes inside a decorator. In a future this will permit me to access to few definition and hide some useless code.

The code must work like this:

def division_error(The_Object_Iteself):
    def inner_function(function):
        def wrapper(*args, **kwargs):
            try:
                function(*args, **kwargs)
            except ZeroDivisionError as err:
                print(f"{The_Object_Iteself.__name__}: impossible division by zero")
        return wrapper
    return inner_function


class Tast:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @division_error(The_Object_Iteself)
    def divide(self):
        return self.a / self.b


tast = Tast(12, 1)
print(tast.divide())

They have another possibility, it's to access it from the decorator itself by not passing the object as arguments of the decorator like the code next

from functools import wraps


def division_error(function):
    def wrapper(*args, **kwargs):
        try:
            function(*args, **kwargs)
        except ZeroDivisionError as err:
            print(f"{Tast.__object__.__name__}: Division by zero error")
    return wrapper


class Tast:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @division_error
    def divide(self):
        return self.a / self.b


tast = Tast(12, 0)
print(tast.divide())

I'm not sure of the manner who can do this, otherwise, I do not now how to do this.

Thanks for your time.

Upvotes: 0

Views: 43

Answers (1)

Patrik Polakovic
Patrik Polakovic

Reputation: 571

self instance can be captured inside wrapper. It's first parameter - args[0]. However, this approach works only when wrapping class methods.

def division_error(function):
    def wrapper(*args, **kwargs):
        instance = args[0]

        try:
            function(*args, **kwargs)
        except ZeroDivisionError as err:
            print(f"{instance.__class__.__name__}: Division by zero error")
    return wrapper

Upvotes: 1

Related Questions