user975135
user975135

Reputation:

function to print current module's name, also when called from another module

def a():
    print __name__

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

"Correct" module name should always be the one it is called from.

Upvotes: 3

Views: 148

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226296

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

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

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

Upvotes: 1

Related Questions