toggling decorators

后端 未结 7 1847
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 18:37

What\'s the best way to toggle decorators on and off, without actually going to each decoration and commenting it out? Say you have a benchmarking decorator:



        
相关标签:
7条回答
  • 2021-01-04 18:40

    I think you should use a decorator a to decorate the decorator b, which let you switch the decorator b on or off with the help of a decision function.

    This sounds complex, but the idea is rather simple.

    So let's say you have a decorator logger:

    from functools import wraps 
    def logger(f):
        @wraps(f)
        def innerdecorator(*args, **kwargs):
            print (args, kwargs)
            res = f(*args, **kwargs)
            print res
            return res
        return innerdecorator
    

    This is a very boring decorator and I have a dozen or so of these, cachers, loggers, things which inject stuff, benchmarking etc. I could easily extend it with an if statement, but this seems to be a bad choice; because then I have to change a dozen of decorators, which is not fun at all.

    So what to do? Let's step one level higher. Say we have a decorator, which can decorate a decorator? This decorator would look like this:

    @point_cut_decorator(logger)
    def my_oddly_behaving_function
    

    This decorator accepts logger, which is not a very interesting fact. But it also has enough power to choose if the logger should be applied or not to my_oddly_behaving_function. I called it point_cut_decorator, because it has some aspects of aspect oriented programming. A point cut is a set of locations, where some code (advice) has to be interwoven with the execution flow. The definitions of point cuts is usually in one place. This technique seems to be very similar.

    How can we implement it decision logic. Well I have chosen to make a function, which accepts the decoratee, the decorator, file and name, which can only say if a decorator should be applied or not. These are the coordinates, which are good enough to pinpoint the location very precisely.

    This is the implementation of point_cut_decorator, I have chosen to implement the decision function as a simple function, you could extend it to let it decide from your settings or configuration, if you use regexes for all 4 coordinates, you will end up with something very powerful:

    from functools import wraps
    

    myselector is the decision function, on true a decorator is applied on false it is not applied. Parameters are the filename, the module name, the decorated object and finally the decorator. This allows us to switch of behaviour in a fine grained manner.

    def myselector(fname, name, decoratee, decorator):
        print fname
    
        if decoratee.__name__ == "test" and fname == "decorated.py" and decorator.__name__ == "logger":
            return True
        return False 
    

    This decorates a function, checks myselector and if myselector says go on, it will apply the decorator to the function.

    def point_cut_decorator(d):
        def innerdecorator(f):
            @wraps(f)
            def wrapper(*args, **kwargs):
                if myselector(__file__, __name__, f, d):
                    ps = d(f)
                    return ps(*args, **kwargs)
                else:
                    return f(*args, **kwargs)
            return wrapper
        return innerdecorator
    
    
    def logger(f):
        @wraps(f)
        def innerdecorator(*args, **kwargs):
            print (args, kwargs)
            res = f(*args, **kwargs)
            print res
            return res
        return innerdecorator
    

    And this is how you use it:

    @point_cut_decorator(logger)
    def test(a):
        print "hello"
        return "world"
    
    test(1)
    

    EDIT:

    This is the regular expression approach I talked about:

    from functools import wraps
    import re
    

    As you can see, I can specify somewhere a couple of rules, which decides a decorator should be applied or not:

    rules = [{
        "file": "decorated.py",
        "module": ".*",
        "decoratee": ".*test.*",
        "decorator": "logger"
    }]
    

    Then I loop over all rules and return True if a rule matches or false if a rule doesn't matches. By making rules empty in production, this will not slow down your application too much:

    def myselector(fname, name, decoratee, decorator):
        for rule in rules:
            file_rule, module_rule, decoratee_rule, decorator_rule = rule["file"], rule["module"], rule["decoratee"], rule["decorator"]
            if (
                re.match(file_rule, fname)
                and re.match(module_rule, name)
                and re.match(decoratee_rule, decoratee.__name__)
                and re.match(decorator_rule, decorator.__name__)
            ):
                return True
        return False
    
    0 讨论(0)
  • 2021-01-04 18:41

    another straight way:

    # mymodule.py
    from deco import benchmark
    
    class foo(object):
    
      def f():
        # code
    
      if <config.use_benchmark>:
        f = benchmark(f)
    
      def g():
        # more code
    
      if <config.use_benchmark>:
        g = benchmark(g)
    
    0 讨论(0)
  • 2021-01-04 18:43

    I would implement a check for a config file inside the decorator's body. If benchmark has to be used according to the config file, then I would go to your current decorator's body. If not, I would return the function and do nothing more. Something in this flavor:

    # deco.py
    def benchmark(func):
      if config == 'dontUseDecorators': # no use of decorator
          # do nothing
          return func
      def decorator(): # else call decorator
          # fancy benchmarking 
      return decorator
    

    What happens when calling a decorated function ? @ in

    @benchmark
    def f():
        # body comes here
    

    is syntactic sugar for this

    f = benchmark(f)
    

    so if config wants you to overlook decorator, you are just doing f = f() which is what you expect.

    0 讨论(0)
  • 2021-01-04 18:53

    I've been using the following approach. It's almost identical to the one suggested by CaptainMurphy, but it has the advantage that you don't need to call the decorator like a function.

    import functools
    
    class SwitchedDecorator:
        def __init__(self, enabled_func):
            self._enabled = False
            self._enabled_func = enabled_func
    
        @property
        def enabled(self):
            return self._enabled
    
        @enabled.setter
        def enabled(self, new_value):
            if not isinstance(new_value, bool):
                raise ValueError("enabled can only be set to a boolean value")
            self._enabled = new_value
    
        def __call__(self, target):
            if self._enabled:
                return self._enabled_func(target)
            return target
    
    
    def deco_func(target):
        """This is the actual decorator function.  It's written just like any other decorator."""
        def g(*args,**kwargs):
            print("your function has been wrapped")
            return target(*args,**kwargs)
        functools.update_wrapper(g, target)
        return g
    
    
    # This is where we wrap our decorator in the SwitchedDecorator class.
    my_decorator = SwitchedDecorator(deco_func)
    
    # Now my_decorator functions just like the deco_func decorator,
    # EXCEPT that we can turn it on and off.
    my_decorator.enabled=True
    
    @my_decorator
    def example1():
        print("example1 function")
    
    # we'll now disable my_decorator.  Any subsequent uses will not
    # actually decorate the target function.
    my_decorator.enabled=False
    @my_decorator
    def example2():
        print("example2 function")
    

    In the above, example1 will be decorated, and example2 will NOT be decorated. When I have to enable or disable decorators by module, I just have a function that makes a new SwitchedDecorator whenever I need a different copy.

    0 讨论(0)
  • 2021-01-04 18:53

    Here is what I finally came up with for per-module toggling. It uses @nneonneo's suggestion as a starting point.

    Random modules use decorators as normal, no knowledge of toggling.

    foopkg.py:

    from toggledeco import benchmark
    
    @benchmark
    def foo():
        print("function in foopkg")
    

    barpkg.py:

    from toggledeco import benchmark
    
    @benchmark
    def bar():
        print("function in barpkg")
    

    The decorator module itself maintains a set of function references for all decorators that have been disabled, and each decorator checks for its existence in this set. If so, it just returns the raw function (no decorator). By default the set is empty (everything enabled).

    toggledeco.py:

    import functools
    
    _disabled = set()
    def disable(func):
        _disabled.add(func)
    def enable(func):
        _disabled.discard(func)
    
    def benchmark(func):
        if benchmark in _disabled:
            return func
        @functools.wraps(func)
        def deco(*args,**kwargs):
            print("--> benchmarking %s(%s,%s)" % (func.__name__,args,kwargs))
            ret = func(*args,**kwargs)
            print("<-- done")
        return deco
    

    The main program can toggle individual decorators on and off during imports:

    from toggledeco import benchmark, disable, enable
    
    disable(benchmark) # no benchmarks...
    import foopkg
    
    enable(benchmark) # until they are enabled again
    import barpkg
    
    foopkg.foo() # no benchmarking 
    barpkg.bar() # yes benchmarking
    
    reload(foopkg)
    foopkg.foo() # now with benchmarking
    

    Output:

    function in foopkg
    --> benchmarking bar((),{})
    function in barpkg
    <-- done
    --> benchmarking foo((),{})
    function in foopkg
    <-- done
    

    This has the added bug/feature that enabling/disabling will trickle down to any submodules imported from modules imported in the main function.

    EDIT:

    Here's class suggested by @nneonneo. In order to use it, the decorator must be called as a function ( @benchmark(), not @benchmark ).

    class benchmark:
        disabled = False
    
        @classmethod
        def enable(cls):
            cls.disabled = False
    
        @classmethod
        def disable(cls):
            cls.disabled = True
    
        def __call__(cls,func):
            if cls.disabled:
                return func
            @functools.wraps(func)
            def deco(*args,**kwargs):
                print("--> benchmarking %s(%s,%s)" % (func.__name__,args,kwargs))
                ret = func(*args,**kwargs)
                print("<-- done")
            return deco
    
    0 讨论(0)
  • 2021-01-04 18:54

    You could add the conditional to the decorator itself:

    def benchmark(func):
        if not <config.use_benchmark>:
            return func
        def decorator():
        # fancy benchmarking 
        return decorator
    
    0 讨论(0)
提交回复
热议问题