Python: determine actual current module (not __main__)

I actually ran across this same problem.

What I used was:

return os.path.splitext(os.path.basename(__main__.__file__))[0]

Which is effectively the same as your "hack." Honestly, I think its the best solution.


I know this is outdated but I found a simpler solution in Python3 that worked for me. Long story short, there's the object's __spec__ which also stores the actual module name instead of being "__main__".

import inspect
if obj.__class_.__module__ == "__main__":
    print(inspect.getmodule(obj).__spec__.name)