Search code examples
pythondecorator

Clear list inside decorator from global scope


def outer(func):
    a = []

    def inner():
        func()
        a.append('work')
        print(a)
    return inner


@outer
def test():
    print('TEST')


test()
test()

# *1

test() # *2

*1 here I want clear list a inside a decorator *2 so here must be a new list a inside outer

Is it posible to clear list a, in global scope? If yes, how do it correct.


Solution

  • You can add a parameter to the wrapper function specifying whether to clear a before/after the original function executes.

    def outer(func):
        a = []
    
        def inner(clear=False):
            func()
            a.clear() if clear else a.append('work')
            print(a)
        return inner
    
    @outer
    def test():
        print('TEST')
    
    test()
    test(clear=True)
    # *1
    test() # *2
    
    

    Result:

    TEST
    ['work']
    TEST
    []
    TEST
    ['work']