I recently found myself in a situation where knowing the execution context of a function became necessary. It took me several hours to learn about this functionality, despite many cleverly-crafted Google searches. So, being the generous person I am, I want to share my findings.
My particular use case required that a function behave differently depending on whether it was called in an exec call. Specifics beyond that are not important for this article. Here's an example of how I was able to get my desired behavior.
import inspect def is_exec(): caller = inspect.currentframe().f_back module = inspect.getmodule(caller) if module is None: print "I'm being run by exec!" else: print "I'm being run by %s" % module.__name__ def main(): is_exec() exec "is_exec()" if __name__ == '__main__': main()
The output of such a script would look like this:
$ python is_exec.py I'm being run by __main__ I'm being run by exec!
It's also interesting to note that when you're using the Python interactive interpreter, calling the is_exec function from the code above will tell you that you are indeed using exec.
Some may argue that modifying behavior as I needed to is dirty, and that if your system requires such code, you're doing it wrong. Well, you could apply this sort of code to situations that have nothing to do with exec. Perhaps you want to determine which part of your product is using a specific function the most. Perhaps you want to get additional debugging information that isn't immediately obvious.
Just like always, I want to add the disclaimer that there may be other ways to do this and there probably are. However, this is the way that worked for me. I'd still be interested to here about other solutions you may have encountered for this problem.
On a side note, if you're up for some slightly advanced Python mumbo jumbo, I suggest diving into the inspect documentation.