Question

I'm still very new to Python. Given a function that has decorators, is it possible for the function to access them its body?

(from a Fabric script)

@task
@roles('qa-env')
def deploy_qa():
    #-----------------------------------------------------------------------
    # Is there a way to get access to the @roles decorator as an array here?
    #-----------------------------------------------------------------------
    deployer.configureEnv('qa-env')
    deployer.installApp1()
    deployer.installApp2(True)
Was it helpful?

Solution

No, the function does not know where it is being called from or whom holds references to it.

At best you can access the parent calling frame (with sys._getframe(1)), but that is not necessarily a decorator.

Generally, if your function needs access to a value from the calling frame, it is best to just pass it in. Have the roles decorator call the wrapped function with an extra argument, for example.

OTHER TIPS

It is doable, in CPython at least, but dirty. You can inspect stack trace, get its locals, find out what exactly is this object, etc, etc.

But if you need to do this, you are probably doing something wrong and your solution should be changed.

Explicit is better than implicit - one of basic python concepts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top