[Python] How to access parent decorator variable in child decorator

Discussão em 'Python' iniciado por Stack, Agosto 21, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a decorator in python. To avoid duplicating code I am inheriting a parent decorator which has a nonlocal variable defined. I am not able to get the exact behaviour in my child decorator as I am not able to modify this variable in parent decorator.

    def parentDecorator(func):
    initial=False
    def wrapped(*args,**kwargs):
    nonlocal initial
    if initial:
    print("gettting executed after initial call")
    return func(*args,**kwargs)
    else:
    print("getting executed before initial call")
    initial=True
    res=func(*args,**kwargs)
    return res
    return wrapped

    def evaluateCondition():
    return True

    def childDecorator(func):
    def wrapped(*args,**kwargs):
    if evaluateCondition():
    myFunc=parentDecorator(func)
    return myFunc(*args,**kwargs)
    else:
    print("do nothing")
    return wrapped

    class decoratorTestClass():
    def __init__(self):
    print('init called')

    @childDecorator
    def execute(self):
    print("Hello from execute function")

    dc=decoratorTestClass()
    dc.execute() # this should be called before initialized
    dc.execute() # this should be called after initialized


    In both the cases the function is getting printed in the else call in the parent decorator. How can i achieve this? I cant change anythin in parent decorator

    Continue reading...

Compartilhe esta Página