As discussed, an option to display the debug of variables is by using the inspect
. Using the inspect.stack
function you can check the context from which the function was executed and access local and global variables in this context. So, instead of passing the variable itself to function, you can only pass its name so that the function will be in charge of accessing its value by inspection. For this example I have also used the module tabulate
to format the output easily and legibly.
import inspect
import tabulate
def debug(*args):
# Busca o contexto de quem chamou a função debug:
context = inspect.stack()[1][0]
# Obtém detalhes de onde foi executado o debug:
filename = context.f_code.co_filename
linenumber = context.f_lineno
# Resultados a serem exibidos:
result = []
# Percorre todas as variáveis a serem exibidas:
for name in args:
# Verifica se é uma variável local no contexto:
if name in context.f_locals:
result.append([name, context.f_locals[name]])
# Verifica se é uma variável global no contexto:
elif name in context.f_globals:
result.append([name, context.f_globals[name]])
# Variável não encontrada no contexto:
else:
result.append([name, 'Não encontrada'])
# Exibe os resultados em forma de tabela:
print(f'[DEBUG] {filename} ({linenumber})')
print(tabulate.tabulate(result, headers=['Variável', 'Valor']))
An example usage would be:
>>> x, y, nome = 1, 2, 'Anderson Carlos Woss'
>>> debug('x', 'y', 'nome', 'foo')
[DEBUG] python (34)
Variável Valor
---------- --------------------
x 1
y 2
nome Anderson Carlos Woss
foo Não encontrada
See working at Repl.it
Example calling within a function
Doing debug
of a local variable and a global variable:
autor = "Anderson Carlos Woss"
def hello(nome):
debug('nome', 'autor')
print(f'Olá, {nome} (por {autor})')
hello('John Doe')
See working at Repl.it
The output will be:
[DEBUG] python (37)
Variável Valor
---------- --------------------
nome John Doe
autor Anderson Carlos Woss
Olá, John Doe (por Anderson Carlos Woss)
However, for expression, such as x+y*2
, the function will not work. It is possible to implement the function for this, but I believe it will be impractical. It will be much simpler for you to assign the expression to another variable and pass it to the function. For example:
>>> x, y = 1, 2
>>> x_plus_2y = x + 2*y
>>> debug('x', 'y', 'x_plus_2y')
Displaying:
[DEBUG] python (38)
Variável Valor
---------- -------
x 1
y 2
x_plus_2y 5