How to get the name of the python function parent

Asked

Viewed 237 times

1

Fala, Povo!

I have a log - add_log() - add function that takes a title, status and Obs to register in a txt file along with the time.

I wonder if there is any way to get the name of the parent function in which add_log() is called.

Ex:

def Soma(a,b):
    try:
        return a+b
    except:
       add_log() #add_log recebe Soma no parâmetro mida sem precisar passar 

>>> '12:09:18.3544 Soma() - OK'
import datetime


def getnow():
    return str(datetime.datetime.now())[:24].split()


def add_log(media,status,obs=""):
    path = '../logs/{}.txt'.format(getnow()[0])
    arq = open(path,'a+')
    arq.write('{} {} - {} - {}'.format(getnow()[1],media,status,obs).strip().strip('-')+'\n')
```

0

2 answers

4


You can use the module inpect for that. With it you can get the stack up to its function add_log and, from it, find out who called the function. For this, we use the function inpect.stack, that returns a list of named tuples, FrameInfo, the first position being the current function and the last the function which started the stack. In this case, as only the parent function interests us, we can take position 1:

import inspect

def foo():
    add_log()

def add_log():
    stack = inspect.stack()

    try:
        print('Função mãe:', stack[1].function)
    except KeyError:
        print('Função mãe não encontrada')

See working on Repl.it

When calling the function foo, foo(), the exit Função mãe: foo is produced by the function add_log.

Other than that, you can get the file name and the number of the line where this call occurs, as I have shown in Debug showing variable name and value?

0

Hello! I believe that using the resources of python for such a need will be more fruitful...

The logging package, brings functionalities to record activities already implemented, fitting only to apply them in the best way to our code.

Follow fully customizable example!

import logging

logging.basicConfig(format='%(asctime)s - %(levelname)s -  %(funcName)s - %(message)s', level=logging.INFO,
                    datefmt='%d-%b-%y %H:%M:%S')


def soma(a, b):
    try:
        r = a + b
        logging.info(f'resultado: {r}')
        return r
    except TypeError:
        logging.error("deu ruim", exc_info=True)


if __name__ == '__main__':
    soma(1, 2)
    soma(1.2, 2.1)
    soma('a', 'b')
    soma('', 2)

Exit:

15-May-19 07:03:34 - INFO -  soma - resultado: 3
15-May-19 07:03:34 - INFO -  soma - resultado: 3.3
15-May-19 07:03:34 - INFO -  soma - resultado: ab
15-May-19 07:03:34 - ERROR -  soma - deu ruim
Traceback (most recent call last):
  File "/home/brito/projetos/saj_projects/exemplos/me/_logging/sof_pt_383625.py", line 11, in soma
    r = a + b
TypeError: can only concatenate str (not "int") to str

To persist in file just change the logging configuration, and add the parameters filename and filemode as in the example in: https://repl.it/@britodfbr/i383625

More details in the official documentation at https://docs.python.org/3/library/logging.html, and a detailed tutorial on https://docs.python.org/3/library/logging.html.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.