2

How would I return a variable name in a function. E.g. If I have the function:

def mul(a,b):
   return a*b

a = mul(1,2); a
b = mul(1,3); b
c = mul(1,4); c

This would return:

2
3
4

I would like it to return:

a = 2
b = 3
c = 4

How would I do this?

ponzi34
  • 29
  • 1
  • 2
  • 3
    use `print("a = " + str(a))`, `print("b = " + str(b))` ... – MEE Jan 29 '18 at 18:16
  • 1
    If you want to dynamically print out the name: look at this: https://stackoverflow.com/questions/544919/can-i-print-original-variables-name-in-python – MEE Jan 29 '18 at 18:17
  • @MEE I want to implement it in the function – ponzi34 Jan 29 '18 at 18:18
  • In which function? Your above code is only working in interactive mode. There is no print function called. If you want to create a function `printWithName(x)` that prints the name of x and the value of x look at the above link – MEE Jan 29 '18 at 18:19
  • Possible duplicate of [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – MEE Jan 29 '18 at 18:20
  • 1
    `mul` has (and can have, short of introspecting on the code in which it appears) *no* idea what will be done with its return variable, let alone the name of a variable it might be assigned to. – chepner Jan 29 '18 at 18:24

2 Answers2

3

Unfortunately, you are unable to go "backwards" and print the name of a variable. This is explained in much further detail in this StackOverflow post.

What you could do is put the variable names in a dictionary.

dict = {"a":mul(1,2), "b":mul(1,3), "c":mul(1,4)}

From there you could loop through the keys and values and print them out.

for k, v in dict.items():
    print(str(k) + " = " + str(v))

Alternatively, if you wanted your values ordered, you could put the values into a list of tuples and again loop through them in a for loop.

lst = [("a", mul(1,2)), ("b", mul(1,3)), ("c",mul(1,4))]
peachykeen
  • 4,143
  • 4
  • 30
  • 49
0

Here is how to do it with python-varname package:

from varname import varname

def mul(a, b):
   var = varname()
   return f"{var} = {a*b}"

a = mul(1,2)
b = mul(1,3)
c = mul(1,4)

print(a) # 'a = 2'
print(b) # 'b = 2'
print(c) # 'c = 2'

The package is hosted at https://github.com/pwwang/python-varname.

I am the author of the package. Let me know if you have any questions using it.

Panwen Wang
  • 3,573
  • 1
  • 18
  • 39