Created
December 4, 2023 17:19
-
-
Save pytlv/0d7cdf5120d3d16f38f38a2a6f65b34a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Kindall - https://stackoverflow.com/questions/8315389/how-do-i-print-functions-as-they-are-called | |
| def tracefunc(frame, event, arg, indent=[0]): | |
| if event == "call": | |
| indent[0] += 2 | |
| print("-" * indent[0] + "> call function", frame.f_code.co_name) | |
| elif event == "return": | |
| print("<" + "-" * indent[0], "exit function", frame.f_code.co_name) | |
| indent[0] -= 2 | |
| return tracefunc | |
| import sys | |
| sys.setprofile(tracefunc) | |
| main() # or whatever kicks off your script | |
| ''' | |
| Note that a function's code object usually has the same name as the associated function, but not always, | |
| since functions can be created dynamically. | |
| Unfortunately, Python doesn't track the function objects on the stack (I've sometimes fantasized about submitting a patch for this). | |
| Still, this is certainly "good enough" in most cases. | |
| If this becomes an issue, you could extract the "real" function name from the source code—Python does track the | |
| filename and line number—or ask the garbage collector find out which function object refers to the code object. | |
| There could be more than one function sharing the code object, but any of their names might be good enough. | |
| ''' | |
| ''' | |
| This is awesome. I ended up adding | |
| os.path.basename(frame.f_code.co_filename) to this trace function to print the file containing the function called. – | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment