Am1rr3zA Am1rr3zA - 25 days ago 9
Python Question

Python decorator that let's method run or raise an exception

I need to have a decorator that takes an argument and if the method should be allowed to run (based on some simple logic) or raise an exception. yet I have no idea how can I write this decorator.

class One(obj):
trend = "trend"
@myDecorator(self.trend)
def click_button(self):
clickable_element = self.driver.find_element_by_id(self.trend)
clickable_element.click()
return self


class Two(obj):
map = "map"

@myDecorator(self.map)
def click_button(self):
clickable_element = self.driver.find_element_by_id(self.map)
clickable_element.click()
return self


The logic should be something like this:

def my Decorator(arg):
if arg:
"run the method"
else:
raise "Exception"

Answer
def parametrised_decorator(parameter):
    def parametrised(function):
        @functools.wraps(function)
        def inner(*args, **kwargs):
            if parameter:
                return function(*args, **kwargs)
            else:
                raise Exception()

        return inner

    return parametrised