Function to print the current module name, also when called from another module

def a():
    print __name__

      

Is there a chance I might have such a function, but print the "correct" module name if imported by another module and called from here?

"Fixed" the name of the module should always be the one from which it is called.

+3


source to share


1 answer


The sys module provides a CPython-specific way to find your caller:

sys._getframe(1).f_globals.get('__name__', '__main__')

      



The _getframe () function is documented here and the frame objects are documented.

+1


source







All Articles