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

大憨熊 提交于 2019-12-02 07:29:12

问题


I need to have a decorator that takes an argument and checks (based on some simple logic) if the method should be allowed to run or raise an exception.

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"

回答1:


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



回答2:


def my_Decorator(arg=None):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if arg:
                return func(*args, **kwargs)

            else:
                raise Exception()

        return wrapper

    return decorator



回答3:


from functools import wraps


def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if kwargs.pop('runit', None):
            return f(*args, **kwargs)
        else:
            raise Exception()
    return wrapper


@my_decorator
def example():
    print('example')


if __name__ == '__main__':
    # runs function
    example(runit=True)
    # runs exception
    example()


来源:https://stackoverflow.com/questions/40597683/python-decorator-that-lets-method-run-or-raise-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!