Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including the current method name when printing in Python

Often times in C programs (and using GCC) I will create a debug print macro that includes the name of the current function. That is, something like:

#define DPRINTF(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

When used, the current function will be prepended to each print, providing more useful debug information at runtime. For example, the following code

#include <stdio.h>

#define DPRINT(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

void testfunction1(){
    DPRINT("Running %d\n",1);
}

void testfunction2(){
    DPRINT("Running %d\n",2);
}

int main(void) {
    DPRINT("Running: %d\n",0);
    testfunction1();
    testfunction2();
    return 0;
}

Would output:

[main] Running: 0
[testfunction1] Running 1
[testfunction2] Running 2

Can something like this be done in Python?

I searched around a bit and found this StackOverflow question explaining how inspect can be used to read names from the stack. However, from what I've found Python does not support macros, so the same form as my C program cannot be used.

Is there some mechanism by which this type of debug printing can be supported? I tried lambdas, but the "function name" in this case prints as "< lambda >".

like image 449
sherrellbc Avatar asked May 28 '26 16:05

sherrellbc


1 Answers

You can inspect the last frame to retrieve the caller name and the rest is simple formatting, something like

import sys

def dprint(fmt=None, *args, **kwargs):
    try:
        name = sys._getframe(1).f_code.co_name
    except (IndexError, TypeError, AttributeError):  # something went wrong
        name = "<unknown>"
    print("[{}] {}".format(name, (fmt or "{}").format(*args, **kwargs)))

def testfunction1():
    dprint("Running {}", 1)

def testfunction2():
    dprint("Running {}", 2)

def main():
    dprint("Running {}", 0)
    testfunction1()
    testfunction2()
    return 0

if __name__ == "__main__":
    main()

# prints:
# [main] Running 0
# [testfunction1] Running 1
# [testfunction2] Running 2
like image 67
zwer Avatar answered May 31 '26 07:05

zwer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!