-2

I have the following code:

var1='aaa'
var2='bbb'
debug(var1, var2)

I would like the debug function to print:

"var1=aaa var2=bbb"

My function currently looks like

def debug(thing1, thing2):
    print(f"{thing1=} {thing2=}")

and outputs:

"thing1=aaa thing2=bbb"

I tried using locals() in the function as well but got the same output. I would like to have "var1" and "var2" in the output without hardcoding them in the print statement.

Lamp
  • 51
  • 7
  • 2
    Use: `print(f"var1={thing1} var2={thing2}")` – S3DEV Nov 09 '20 at 22:15
  • 2
    Multiple variable names can point to a single object. There's no way to know which variable name you're interested in unless you specify. If you need to know the variable names that were passed into a function within the function, you have a problem anyway. – TigerhawkT3 Nov 09 '20 at 22:19
  • @jarmod could you provide an example of pathing both the name and the value? – Lamp Nov 09 '20 at 22:20
  • @S3DEV I would like to dynamically print the function call arguments instead of hardcoding "var1" and "var2" in the print statement. – Lamp Nov 09 '20 at 22:27
  • 1
    Typo: I meant "pass" not "path", of course. Example: `a=1;b=2;debug('a', a, 'b', b)`. But a better solution is for the caller to supply the log format and values e.g. `print("a=%d, b=%d" % (a,b))`. Python doesn't give you access to a variable's name, afaik. Related: https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – jarmod Nov 09 '20 at 22:27
  • @TigerhawkT3 How do I specify the variable name that is used in the function call? The reason I'm doing this is for readability of the print statement. – Lamp Nov 09 '20 at 22:32
  • You specify the variable name you want to print by telling the program what you want. For example, if you want to print `var1`, you tell it `var1`. – TigerhawkT3 Nov 09 '20 at 23:38

1 Answers1

3

You need to come at this problem in a slightly different way. As stated, there is no way for debug to know the variable names.

You need to supply that information:

>>> import pprint
>>> var1 = 'aaa'
>>> var2 = 'bbb'
>>> def debug(**kwargs):
...     pprint.pprint(kwargs, width=20)
... 
>>> debug(var1=var1, var2=var2)
{'var1': 'aaa',
 'var2': 'bbb'}
J_H
  • 17,926
  • 4
  • 24
  • 44