python

[Python] Using inspect.stack() to get module name, path, function name

import pytest
import logging
import inspect

def test_inspect():
    caller = inspect.stack()[1]
    logging.info(f"\nThis is  caller[3]:  {caller[3]}")

    def foo():
        caller = inspect.stack()[1]
        logging.info(f"\nThis is  caller[3] inside function:  {caller[3]}")

        for item in caller:
            logging.info(f"\nThis is  caller item:  {item}")
    foo()
Output
-------------------------------- live log call ---------------------------------
08:14:29 INFO
This is caller[3]: pytest_pyfunc_call
08:14:29 INFO
This is caller[3] inside function: test_inspect
08:14:29 INFO
This is caller item: <frame at 0x11138b740, file '/Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py', line 32, code test_inspect>
08:14:29 INFO
This is caller item: /Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py
08:14:29 INFO
This is caller item: 32
08:14:29 INFO
This is caller item: test_inspect
08:14:29 INFO
This is caller item: [' foo()\n']
08:14:29 INFO
This is caller item: 0
Was this helpful?