0

In my code I have declared a lot of variables, which I like to analyse frequently to check if the values make sense. E.g.

import numpy as np
foo = 8                       # some data
bar = 5
k = np.array([[0, 1],[2,3]])

print('foo:',foo, 'k:',k)     # I write these lines of code a lot

Now I tried to create a function 'jprint' that would be less work for me. The function should automatically to print the variables including their names, like this.

def jprint(*args):
    for arg in args:
        print('?arg_name?',':',arg, end='')  # (end='' suppresses 
                                             # newline, not of importance 
                                             # any further)
    return

jprint(foo,k)
>> foo: 8, k: [[0 1] [2 3]]                  # (on 2 lines probably)

Thus, I need to get both the value of the variable and its name. However, I understand from other similar questions from StackOverflow, that it is very bad to want this.

So I am still searching and wondering. What's the best alternative?

Semi-solution

The first solution I thought of was putting everything in a dictionary, like this

import numpy as np
foo = {'foo',8}                       # some data
bar = {'bar',5}
k = {'k',np.array([[0, 1],[2,3]])}

jprint(foo,k)     
>> foo: 8, k: [[0 1] [2 3]]    

Then all values and keys (or names) are coupled beforehand. However, because I really have a lot of variables, and I create them quite often, this adds up to quite some extra code for every variable assignment. So it doesn't seem to be the ideal solution.

Best solution

I hope I am missing a very elegant solution. Any chance that you know one?

Community
  • 1
  • 1
Jobbert
  • 11
  • 1
  • The dictionary syntax is `{key1:value1, key2:value2, ...}`. Of course you need only one for all parameters. – guidot Jan 08 '19 at 13:13
  • Why are you trying to do this? There are likely more elegant solutions depending on what you're trying to accomplish. – Allen Jan 08 '19 at 13:14
  • "What's the best alternative" [`pdb`](https://docs.python.org/3/library/pdb.html)? –  Jan 08 '19 at 13:15
  • Looks like you would want to use a debugger. For example, take a look at the one from PyCharm: https://www.jetbrains.com/help/pycharm/part-1-debugging-python-code.html Is this what you want? – Georgy Jan 08 '19 at 13:16
  • Be sure to read https://nedbatchelder.com/text/names1.html. Python objects don't know anything about the name(s) that refer to them. – chepner Jan 08 '19 at 13:24
  • Probably you could find this helpful: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Georgy Jan 08 '19 at 13:24
  • I never used a debugger before, but I am now looking into it and from the looks of it, it will solve my problem and ease my life. So thanks! – Jobbert Jan 08 '19 at 14:06

0 Answers0