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.
Jump to turn (10)
- 1In python, how would you get the filename of a module calling a function?
- 2Will that work in both python 2 and python 3?
- 3Isn't "inspect" pretty slow? Would it be faster to use sys.getframe()?
- 4How would you get all function objects from a module?
- 5I have this "getallfunctions" function defined in module A, but I'm calling the
- 6Unfortunately I can't call "allfunctions" in main. I have to call it near the to
- 7There's no clever way to just look at the file and extract all functions? Maybe
- 8Could we make getallfunctions get the calling module dynamically, instead of hav
- 9That works. Now when I load moduleb, I would like the modulea.getallfunctions()
- 10Where is the decorator being applied?
- User
In python, how would you get the filename of a module calling a function?
- Assistant
In Python, you can use the
inspectmodule to get the filename of the module that called a function. Here's a simple example:pythonimport inspect def calling_function(): calling_frame = inspect.currentframe().f_back calling_filename = inspect.getsourcefile(calling_frame) print(f"The function was called from file: {calling_filename}") def main_function(): calling_function() if __name__ == "__main__": main_function()In this example,
inspect.currentframe().f_backgets the frame object that called the current function, and gets the filename of the source file where that frame was created.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.