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:
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
print ("%s=%s" % (name, eval(name)))
(yuck) ? – Proliferousfoo = 1 bar = 2 print(f"{foo=} {bar=}")
in python 3.8? – Tiffa