Python Forum
Show Name of Calling function - Debug aid
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Show Name of Calling function - Debug aid
#1
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:
Output:
(venv) Larz60p@linux-nnem: src:$TestGetPage.py About to fetch file: AreaCodeDatabaseDefinitions.xls calling function: test_get_page (venv) Larz60p@linux-nnem: src:$
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  my debug toys Skaperen 0 2,080 Sep-28-2018, 06:30 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020