Skip to content
Advertisement

Python: Print a variable’s name and value?

When debugging, we often see print statements like these:

JavaScript

How can write a function that will take a variable or name of a variable and print its name and value? I’m interested exclusively in debugging output, this won’t be incorporated into production code.

JavaScript

Advertisement

Answer

You can just use eval:

JavaScript

Or more generally (which actually works in the context of the calling function and doesn’t break on debug('variable'), but only on CPython):

JavaScript

And you can do:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement