Getting a Calling Function’s Module Name in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # In helpers.py import inspect import os def get_wrong_module_name(): return __file__.split(os.path.sep)[-1] def inspect_helper(): """This function is here for no good reason... other than to demonstrate the flexibility of using the inspect solution. """ return inspect.stack()[-1].filename def get_right_module_name(): return inspect_helper() # In main.py import os from helpers import get_bad_module_name, get_right_module_name print("WRONG module name: ", get_wrong_module_name()) print("RIGHT module name: ", get_right_module_name()) # Output: # WRONG module name: helpers.py # RIGHT module name: main.py |