0

g++ has this nice variable PRETTY_FUNCTION that contains the name of the function called. For functions it produces the prototype (e.g., "void foo(long)"). For member functions in classes, the name includes the class name (e.g., "void Foo::foo(long)").

Is there an equivalent in Python. I have been playing around with "sys._getframe()" which gets close, but there doesn't seem to be a similarly simple mechanism that includes the class name when it is a member function.

I like to use this in error handlers.

Surely someone has a magical one-liner for this...

TIA,

-Joe

  • Does this answer your question? [Determine function name from within that function (without using traceback)](https://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback) – davidbak Jun 01 '20 at 01:06
  • Plus https://stackoverflow.com/questions/14094961/python-how-can-i-get-the-class-name-from-within-a-class-method-using-classm for the class name. – davidbak Jun 01 '20 at 01:09
  • I have looked at most of these examples. There are two issues: having it work transparently for class methods and functions (the C++ version does this) and wrapping the function to something user friendly like a variable definition ("__NAME__"). Obviously I can get a this information many ways and write some complicated function, but I was hoping there was something simpler. It seems like such a basic capability. – user3016511 Jun 01 '20 at 03:21

1 Answers1

0

Example Python Code

This is about the closest I can get right now. Search for "<<< here".

Typing Foo.CLNAME is kind of silly. It would be nice if this could somehow be collapsed to an external function and stay outside of the class. There must be a way to do this in Python in a way similar to the way LINE and NAME work.

The implementations of those two are based on code I got from here:

How to determine file, function and line number?

Nice stuff!

-Joe

=====

#!/usr/bin/env python

# import system modules
#
import os
import sys

# define a hack to get the function name
#                                                                             
class __MYNAME__(object):
    def __repr__(self):
        try:
            raise Exception
    except:
        return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)

    def __init__(self):
        pass

__NAME__ = __MYNAME__()

# define a hack to get the line number in a program                            
#                                                                             
class __MYLINE__(object):
    def __repr__(self):
        try:
            raise Exception
        except:
            return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)

__LINE__ = __MYLINE__()

# use these in a function call
#
def joe():
    print("[FUNCTION] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

# use these in a class member function
#
class Foo():

    def __init__(self):
        Foo.__CLNAME__ = self.__class__.__name__

    def joe(self):
        print("[CLASS] name: %s::%s, line: %s" %
              (Foo.__CLNAME__, __NAME__, __LINE__))  # <<< here

#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):

    # main program
    #
    print("[MAIN PROGRAM] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

    # function call
    #
    joe()

    # class member function
    #
    foo = Foo()
    foo.joe()

    # exit gracefully
    #
    sys.exit(os.EX_OK)

#
# end of main

# begin gracefully
#
if __name__ == "__main__":
    main(sys.argv[0:])

#
# end of file