Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Print a variable's name and value?

When debugging, we often see print statements like these:

print x        # easy to type, but no context print 'x=',x   # more context, harder to type 12 x= 12 

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.

debugPrint(x)    #  or debugPrint('x') x=12 
like image 558
Mark Harrison Avatar asked Aug 14 '15 01:08

Mark Harrison


People also ask

How do you print variable names and values in Python?

Using f-strings in Python to print variables is the most commonly used method and I would personally recommend using this method. In this method, an 'f' is placed before the opening quotation mark of a string. Braces {} are placed around the names of variables that you are looking to print.

How do you print a variable name instead of a value?

Then you just have to change the print line from: print(name[6:-1] , ':' , var) , to , print(name[2:-1] , ':' , var) . Enjoy!

How do you print variable names?

Print Variable Name With a Dictionary in Python We stored the variable values as keys and the corresponding variable names as the vnames dictionary values. Whenever we have to print the name of a particular variable, we have to pass the value inside vnames[] .


1 Answers

Python 3.8 f-string = syntax

It has arrived!

#!/usr/bin/env python3 foo = 1 bar = 2 print(f"{foo=} {bar=}") 

output:

foo=1 bar=2  

Added in commit https://github.com/python/cpython/commit/9a4135e939bc223f592045a38e0f927ba170da32 "Add f-string debugging using '='." which documents:

f-strings now support =  for quick and easy debugging -----------------------------------------------------  Add ``=`` specifier to f-strings. ``f'{expr=}'`` expands to the text of the expression, an equal sign, then the repr of the evaluated expression.  So::    x = 3   print(f'{x*9 + 15=}')  Would print ``x*9 + 15=42``. 

so it also works for arbitrary expressions. Nice!

The dream: JavaScript-like dict keys from variable names

I find Python better than JavaScript in almost every sense, but I've grown to really like this JavaScript feature:

let abc = 1 let def = 2 console.log({abc, def}) 

works in JavaScript because {abc, def} expands to {abc: 1, def: 2}. This is just awesome, and gets used a lot in other places of the code besides logging.

Not possible nicely in Python currently except with locals: Python variables as keys to dict