Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading