Am1rr3zA Am1rr3zA - 11 months ago 47
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"
def click_button(self):
clickable_element = self.driver.find_element_by_id(self.trend)
return self

class Two(obj):
map = "map"

def click_button(self):
clickable_element = self.driver.find_element_by_id(
return self

The logic should be something like this:

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

Answer Source
def parametrised_decorator(parameter):
    def parametrised(function):
        def inner(*args, **kwargs):
            if parameter:
                return function(*args, **kwargs)
                raise Exception()

        return inner

    return parametrised