Python3 decorating conditionally?

后端 未结 3 1055
滥情空心
滥情空心 2021-01-01 06:27

Is it possible to decorate a function based on a condition?

a\'la:

if she.weight() == duck.weight(): 
    @burn
def witch():
    pass
3条回答
  •  清酒与你
    2021-01-01 07:16

    It is possible to enable/disable decorators by reassignment.

    def unchanged(func):
        "This decorator doesn't add any behavior"
        return func
    
    def disabled(func):
        "This decorator disables the provided function, and does nothing"
        def empty_func(*args,**kargs):
            pass
        return empty_func
    
    # define this as equivalent to unchanged, for nice symmetry with disabled
    enabled = unchanged
    
    #
    # Sample use
    #
    
    GLOBAL_ENABLE_FLAG = True
    
    state = enabled if GLOBAL_ENABLE_FLAG else disabled
    @state
    def special_function_foo():
        print "function was enabled"
    

提交回复
热议问题