In python, how would you get the filename of a module calling a function?
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
In python, how would you get the filename of a module calling a function?
- Assistant
To get the filename of a module calling a function in Python, you can use the
inspectmodule, which provides functions to retrieve information about live objects such as functions, classes, and methods. Here's a function that returns the filename of the calling module:pythonimport inspect import os def get_calling_module_filename(): """ Returns the filename of the module calling this function. """ # Get the stack frame of the caller frame = inspect.currentframe().f_back # Get the module object of the caller module = inspect.getmodule(frame) # If the module is not defined or has no __file__ attribute, return None if module is None or not hasattr(module, '__file__'): return None # Return the filename of the calling module return os.path.abspath(module.__file__)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.