getting invoking module's name in Python
Question: Is there a more straight-forward way of getting the name of the invoking
module than this:

    
    
    script_file_path = sys.argv[0]
    top_module_name = None
    for frame in reversed(inspect.stack()):
        if frame[1] == script_file_path:
            top_module_name = inspect.getmodule(frame[0]).__name__
    


Answer: I think both of the following are certainly more efficient, and the first
seems a bit more straightforward (at least, you deal with fewer indices, file
paths, etc.). I think the first would work most of the time (but I have not
tested it fully):

    
    
    import inspect
    
    def get_invoking_module():
        frame = inspect.currentframe()
        return frame.f_back.f_globals["__name__"]
    

This should work all the time:

    
    
    def get_invoking_module():
        frame = inspect.currentframe()
        current_module = inspect.getmodule(frame)
        while inspect.getmodule(frame) == current_module:
            frame = frame.f_back                           # walk back up the frames
        if frame:
            return frame.f_globals["__name__"]
    

