import inspect def foo(): s = inspect.stack() print(s[1].code_context()) # this prints 'foo()' foo() # this raises exception because code_context is empty exec('foo()')