As commented, an option to display the debug of variables is using the module inspect
. With the help of function inspect.stack
you can verify the context from which the function was executed and access local and global variables in that context. So, instead of you passing the variable itself to function, you can pass only its name that the function will take charge of accessing the respective value by inspection. For this example I also used the module tabulate
for easy and readable formatting of the output.
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 of use 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 on Repl.it
Call example within a function
Making the debug
of a local and global variable:
autor = "Anderson Carlos Woss"
def hello(nome):
debug('nome', 'autor')
print(f'Olá, {nome} (por {autor})')
hello('John Doe')
See working on Repl.it
The exit will be:
[DEBUG] python (37)
Variável Valor
---------- --------------------
nome John Doe
autor Anderson Carlos Woss
Olá, John Doe (por Anderson Carlos Woss)
But for expression, such as doing x+y*2
the function will not work. It is possible to implement the function for this, but I believe it will be unviable. 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
Problem that when passed to the function, the reference to the value changes, also changing the name. For example, you could define the function
debug(*args)
to receive as many parameters as you need, but the variable becomesargs
and no morex
,y
or an expression. Tox
andy
you can work with the value returned bylocals()
, but as for expression, I don’t know if you can do it; maybe withinspect
, would need to analyze it better.– Woss
i usually do something like print("A",x,y,z,w,p,n); (the A at the beginning is just to know what print is about, in a second I put B, or something that makes sense just to differentiate, because I know what I put inside the print, I don’t need to leave all the strings "cute" (after all is debug right? ). Now, if you need a lot of print all the time, it would be nice to review the methodology.
– Bacco