Python: Print a variable's name and value?

PythonDebugging

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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: https://stackoverflow.com/questions/3972872/python-variables-as-keys-to-dict

Solution 2 - Python

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

Solution 3 - Python

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

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

Solution 4 - Python

import inspect
import re
def debugPrint(x):
    frame = inspect.currentframe().f_back
    s = inspect.getframeinfo(frame).code_context[0]
    r = re.search(r"\((.*)\)", s).group(1)
    print("{} = {}".format(r,x))

This won't work for all versions of python:

inspect.currentframe()

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

Solution 5 - Python

I wrote the following to be able to type something like (at line 41 of file describe.py):

describe('foo' + 'bar')
describe(numpy.zeros((2, 4)))

and see:

describe.py@41 describe('foo' + 'bar') = str(foobar) [len=6]   
describe.py@42 describe(numpy.zeros((2, 4))) = ndarray(array([[0., 0., 0., 0.],
   [0., 0., 0., 0.]])) [shape=(2, 4)]

Here's how:

# Print the line and filename, function call, the class, str representation and some other info

# Inspired by https://stackoverflow.com/a/8856387/5353461
import inspect
import re


def describe(arg):
    frame = inspect.currentframe()
    callerframeinfo = inspect.getframeinfo(frame.f_back)
    try:
        context = inspect.getframeinfo(frame.f_back).code_context
        caller_lines = ''.join([line.strip() for line in context])
        m = re.search(r'describe\s*\((.+?)\)$', caller_lines)
        if m:
            caller_lines = m.group(1)
            position = str(callerframeinfo.filename) + "@" + str(callerframeinfo.lineno)

            # Add additional info such as array shape or string length
            additional = ''
            if hasattr(arg, "shape"):
                additional += "[shape={}]".format(arg.shape)
            elif hasattr(arg, "__len__"):  # shape includes length information
                additional += "[len={}]".format(len(arg))

            # Use str() representation if it is printable
            str_arg = str(arg)
            str_arg = str_arg if str_arg.isprintable() else repr(arg)

            print(position, "describe(" + caller_lines + ") = ", end='')
            print(arg.__class__.__name__ + "(" + str_arg + ")", additional)
        else:
            print("Describe: couldn't find caller context")

    finally:
        del frame
        del callerframeinfo

https://gist.github.com/HaleTom/125f0c0b0a1fb4fbf4311e6aa763844b

Solution 6 - Python

For those who are not using python 3.8 yet, here is an alternative.

This is a modified, shorter version of the accepted answer from a closed 2009 duplicate question found here, (which was also copied with a mistake in the below Aug 14, '15, the mistake being the re contains the hard coded function name 'varname' instead of the function name shown 'getm'). Original found here: https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python?

To explain the re below, the inspect.getframeinfo(inspect.currentframe(), f_back)[3] gives the function signature in a list

['                p(prev)\n']

Casting to str saves you from having to loop through the list of one item. The re looks for an '(' which has to be escaped, the next '(' is to create a group within the match to reference, then [^)] means any character not ')', the '^' means 'not' in this context, brackets [] mean match any character within, and the following '*' is a quantifier for 0 or more times. Then close the group with a ')', match the closing ')' and voila:

def p(x):
    import inspect
    import re
    m = re.search('\(([^)]*)\)',str(inspect.getframeinfo(inspect.currentframe().f_back)[3]))
    print(f' {m.group(1)}: {x}')

Does this work with 2.7? Wait here while I check ... No, seemingly not. I did see one or two other variations that didn't use inspect.getframeinfo(inspect.currentframe().f_back)[3], so perhaps one of those would work. You'd have to check the duplicates and comb through the answers. Also to caution, some answers said to beware of python interpreters that may not be compatible with various solutions. The above worked on

Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Solution 7 - Python

Just developed the answer of @Padraic Cunningham to take arbitrary number of variables. I liked this method since it works just like print(x1, x2, x3) - no need to wrap var names in ''.

import inspect
import re

def prinfo(*args):
    frame = inspect.currentframe().f_back
    s = inspect.getframeinfo(frame).code_context[0]
    r = re.search(r"\((.*)\)", s).group(1)
    vnames = r.split(", ")
    for i,(var,val) in enumerate(zip(vnames, args)):
        print(f"{var} = {val}")
    
x1 = 1
x2 = 2
x3 = 3
prinfo(x1, x2, x3)

Output is:

x1 = 1
x2 = 2
x3 = 3

Solution 8 - Python

Quite ugly , but does the job :

import inspect, re
def getm(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    match = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
    if match:
      return match.group(1)
x=21
search = getm(x);
print (search , '=' , eval(search))

Solution 9 - Python

A simple example would be:

def debugPrint(*expr):
    text = traceback.extract_stack()[-2][3]
    begin = text.find('debugPrint(') + len('debugPrint(')
    end = text.find(')',begin)
    text=[name.strip() for name in text[begin:end].split(',')]
    for t, e in text, expr:
        print(str(t) +  " = " + str(e))

Hope it helps!

Solution 10 - Python

I've just concocted a function like this that prints an arbitrary expression:

import inspect, pprint

def pp(n):
    print()
    print(n,"=")
    f=inspect.stack()[1].frame
    pprint.pprint(eval(n,f.f_globals,f.f_locals))

(I used a blank line before the name and a newline before the value 'cuz in my case, I needed to print large data structures. It's easier to read such an output with the line breaks.)

It's safe as long as you don't pass it untrusted input.

You might also be interested in my dump module. It prints all the object's fields in a human-readable form. Proved extremely useful for debugging.

Solution 11 - Python

Multiple variables (taking @Blender response one step further) :

def debug(variables, sep =''):
        vars = variables.split(',')
        for var in vars:
          print(var, '=', repr(eval(var)), end = sep)

Example:

import bumpy as np
gPrimeLinear = lambda z: np.ones(np.array(z).size)*z
gPrimeSigmoid = lambda z: 1./(1+np.exp(-z))*(1-1./(1+np.exp(-z)))
gPrimeTanh = lambda z: 1- np.tanh(z)**2
z = np.array([ 0.2, 0.4, 0.1])
debug("z, gPrimeLinear(z), gPrimeSigmoid(z), gPrimeTanh(z)", '\n')

This returns:

> z = array([0.2, 0.4, 0.1])  
> gPrimeLinear(z) = array([0.2, 0.4, 0.1]) 
> gPrimeSigmoid(z) = array([0.24751657, 0.24026075, 0.24937604]) 
> gPrimeTanh(z) = array([0.96104298, 0.85563879, 0.99006629])

Solution 12 - Python

When finding the name of a variable from its value,
you may have several variables equal to the same value,
for example var1 = 'hello' and var2 = 'hello'.

My solution to your question:

def find_var_name(val):

    dict_list = []
    global_dict = dict(globals())

    for k, v in global_dict.items():
        dict_list.append([k, v])
   
    return [item for item in dict_list if item[1] == val]

var1 = 'hello'
var2 = 'hello'
find_var_name('hello')

Outputs

[['var1', 'hello'], ['var1', 'hello']]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark HarrisonView Question on Stackoverflow
Solution 1 - PythonCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 2 - PythonBlenderView Answer on Stackoverflow
Solution 3 - PythonAziz AltoView Answer on Stackoverflow
Solution 4 - PythonPadraic CunninghamView Answer on Stackoverflow
Solution 5 - PythonTom HaleView Answer on Stackoverflow
Solution 6 - PythoncharsView Answer on Stackoverflow
Solution 7 - Pythonmsm1089View Answer on Stackoverflow
Solution 8 - Pythonm0bi5View Answer on Stackoverflow
Solution 9 - PythonSujay KumarView Answer on Stackoverflow
Solution 10 - Pythonivan_pozdeevView Answer on Stackoverflow
Solution 11 - PythonchikitinView Answer on Stackoverflow
Solution 12 - PythonAlex RicciardiView Answer on Stackoverflow