How to Print Variable Names in Python

In C, we can use the following snippet to print variable names to debug.

#include <stdio.h>
typedef long long int ll;
#define getName(var)		#var
#define debug(var)		fprintf(stderr,"%s = %lld\n",getName(var),((ll)var));
int main()
{
    int variable = 100;
    debug(variable);
    return 0;
}

Screenshot from 2020-11-20 12-08-18
How do we do the same in Python?

If you are trying to do this, it means you are doing something wrong.
consider using a dict instead.

def show_val(vals, name):
print " Name : " , name, "val : " , vals[name]
vals = {‘a’ : 1, ‘b’ : 2}
show_val(vals, ‘b’)

Output:
Name: b val: 2

My question was not about printing a Dictionary.
What I want is, is there any way to print variable names along with values in Python?
Say I have the following C code snippet

#include <stdio.h>
typedef long long int ll;
#define getName(var)		#var
#define debug(var)		fprintf(stderr,"%s = %lld\n",getName(var),((ll)var));
int main()
{
    int num = 5;
    for(int iter = 0; iter<num; iter++)
        debug(iter);
    return 0;
}

There is nothing printed to stdout, but the following is printed to stderr.

iter = 0
iter = 1
iter = 2
iter = 3
iter = 4

In the same way, I would use stderr in python, but the syntax is little big.

from sys import stderr
for iter in range(5):
    stderr.write("iter = "+str(iter)+'\n')

Even this code would write the same to stderr. But see the way I wrote it in C vs in python.
I need a simpler way to do this, if possible.
Please help @carre, @sebastian, @ssrivastava990

I think this is not possible to do in python. :frowning:

1 Like

Okay :slightly_frowning_face:

1 Like

I am not if I understood your question correctly, but I think this is what you’re looking for.
from pdb import set_trace

And you call the set_trace() function anywhere in your code, with which you can check the values of any variable/expression upto that point of execution(usually done just above the line where you encounter an error)

2 Likes

That’s good. I should have rephrased my post title to something like “Debugging in Python for CP”. Well, Thanks a lot for it.