Question

How does the control flow work in case of decorators ? Is there anyway I can modify calleedec and make it not return to caller after its getting invoked ? Its not my desired scenario I see a similar bug so wondering if thats possible ? Isn't it just like normal functions ?

Trying to debug an issue - we hit the first pdb but not the second pdb as in the scenario below ?

Both are decorated functions .

@cooldec()
def caller():
    import pdb;pbd.set_trace()  # Hits here
    callee()
    import pdb;pdb.set_trace() # Not here

@calleedec()
def callee():
    return "Okay

Edit:

Raising Error is one scenario but no error trace .

I can see a case where callee's decorator in an infinite loop or is not able to do its job (taking long time) , this can happen .

Était-ce utile?

La solution

Decorated functions are just plain functions, and have nothing special to them regarding program flow.

When in doubt, try to expand the decorator and see if that is clearer:

def calleedec(callee_fn):
    def wrapped():
        print("Running the callee")
        callee_fn()
    return wrapped

def callee():
    return "Okay"

callee = calleedec(callee)

def cooldec(fn):
    def wrapped():
        print("Running the caller")
        return fn()
    return wrapped

@cooldec
def caller():
    print("caller: start")
    callee()
    print("caller: end")

caller()

# Running the caller
# caller: start
# Running the callee
# caller: end

To avoid the callee hijacking the flow and not returning to the caller function you would need to do some serious black magic with the stack. So I don't think you should worry about this.

If you are not hitting the second pdb breakpoint, something may be happening in your callee function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top