Show Name of Calling function - Debug aid - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Show Name of Calling function - Debug aid (/thread-12143.html) |
Show Name of Calling function - Debug aid - Larz60+ - Aug-11-2018 There is a method that I use to determine what function or method is calling another function or method, during initial testing of a program. This is very easy to do, and I take it for granted, but just thought new programmers may not be aware of how this is done. simply import inspect, and add the line: print(f'calling function: {inspect.stack()[1][3]}')at the beginning of the method you are testing Here's an example you can run: import requests from pathlib import Path from time import sleep import inspect class TestGetPage: def __init__(self): self.test_get_page() def get_page(self, url, savefile, unconditional=False): print(f'About to fetch file: {savefile}') print(f'calling function: {inspect.stack()[1][3]}') page = None havefile = savefile.exists() if unconditional or (not unconditional and not havefile): response = requests.get(url) if response.status_code == 200: page = response.content with savefile.open('wb') as fp: fp.write(page) sleep(2) else: if havefile: with savefile.open('rb') as fp: page = fp.read() return page def test_get_page(self): url = 'https://www.nationalnanpa.com/area_codes/AreaCodeDatabaseDefinitions.xls' savefile = Path('.') / 'AreaCodeDatabaseDefinitions.xls' self.get_page(url, savefile) if __name__ == '__main__': TestGetPage()output:
|