There is no way to make this code, as presented, have any output -- the body of g (including the decorator you'd like to do the printing) simply DOESN'T execute until g is called. I assume you do not literally intend for "this code" on its own to output anything, but rather intend to add a call such as C.C2().g() [which will actually do the output].
There's not really a very efficient way to do this -- you (well, the decorator;-) must start at the module level (which you can identify through the globals of f
, the decorator's argument: its name is f.func_globals['__name__']
and via its name you can look it up in sys.modules
), then you must walk down every possible chain of names until you locate your calling function (e.g. via the inspect module in the standard library). Note also that nested functions are a particular headache in several corner cases.