How can I get the class name of the associated method from the interpreter stack?

I have an amazing little function that looks like this:

def verbose_print(message, *args, **kwargs):
    """Prints `message` with a helpful prefix when in verbose mode

    Args:
        message (str): The message to print. Can be a format string, e.g.
            `A %s with some %s in it`
        *args: Variables for the message format
        **kwargs: Keyword variables for the message format
    """

    # Only print when in verbose mode
    if not config.verbose:
        return

    # Ready a prefix for the message
    try:
        s = inspect.stack()
        module_name = inspect.getmodule(s[1][0]).__name__
        func_name = s[1][3]
        prefix = '### %s->%s' % (module_name, func_name)
    except Exception as e:
        prefix = '### [stack unavailable]'

    if args:
        message = message % args
    elif kwargs:
        message = message % kwargs

    print '%s: %s' % (prefix, message)

The point of the function is that I can call it from anywhere with a message, and if detailed mode is set in my project configuration file, all messages will be printed with a useful prefix to show where it was called. Here is an example of some output:

### avesta.webserver-> check_login: Checking login for client at 127.0.0.1
### avesta.webserver-> check_login: Found credentials cookie with username: tomas, token: blablabla
### avesta.webserver-> check_login: Login valid, refreshing session
### avesta.webserver-> get_flash_memory: Fetched flash data: None
### avesta.webserver->get: Fetched data from empty path ('previous_values', 'name'), returning ''
### avesta.webserver->get: Fetched data from empty path ('previous_values', 'description'), returning ''
### avesta.webserver->get: Fetched data from empty path ('validation_errors', 'name'), returning ''

"### module- > function: message".

, . "get" , . , , , , :

"### module- > ClassName.function"

, :

  • , ,
  • , , ?

, .

+5
1

, , , . bound, boundMethod.im_class.__name__. , , , .

! inspect getargvalues. , , "". , "self" locals dict, . try :

s = inspect.stack()
module_name = inspect.getmodule(s[1][0]).__name__
func_name = s[1][3]
arginfo = inspect.getargvalues(s[1][0])
if len(arginfo.args) > 0 and arginfo.args[0] == "self":
    func_name = "%s.%s" (arginfo.locals["self"].__class__.__name__, func_name)
prefix = '### %s->%s' % (module_name, func_name)
+5

All Articles