In python, how would you get the filename of a module calling a function?
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 that is calling a function, you can use the
inspectmodule in Python. Here's a simple example:pythonimport inspect, os def my_function(): # Your function code here pass def caller(): caller_frame = inspect.stack()[1] caller_file = os.path.abspath(caller_frame[0]) print(f"The calling module is: {os.path.basename(caller_file)}") # Call the function and print the calling module caller() my_function()In this example,
caller()function will print the name of the module that called it. When you callmy_function(), it will print nothing because it doesn't call any other functions.Please note that this method works for functions within the same module. If you want to get the calling module from a function in one module that is called from another module, you should structure your code in a way that allows for proper traceback. For example, you could pass the filename as an argument to the function or use a decorator to store the filename.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.