Python: Print a variable's name and value?

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


You can just use eval:

def debug(variable):
    print variable, '=', repr(eval(variable))

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

from __future__ import print_function

import sys

def debug(expression):
    frame = sys._getframe(1)

    print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))

And you can do:

>>> x = 1
>>> debug('x + 1')
x + 1 = 2

Use the latest f'{var = }' feature in Python3.8 for example:

>>> a = 'hello'
>>> print(f'{a = }')
a = 'hello'