-4

I am trying to define the function which returns the name of variables.

>>> def function(x):
...     return(str(x))
... 
>>> a = 1
>>> function(a)
'1'

I want to define the following function. How can I define it?

>>> a = 1
>>> function(a)
a = 1
h3480
  • 13
  • 3
  • 1
    What shall the function print for `a = 1; b = a; function(a)`? – timgeb Sep 30 '18 at 15:19
  • Can you please explain why exactly you need this to prevent the XY problem? – OneCricketeer Sep 30 '18 at 15:19
  • I'd prefer to tag this question as a 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), and in particular to point the OP to [this answer](https://stackoverflow.com/a/18425275/2749397): _"a name is a one-way reference to an object."_ – gboffi Sep 30 '18 at 15:33

1 Answers1

1

What you're asking for isn't possible as the input argument is evaluated before it feeds your function. In other words, the 'a' variable name is lost, only the value 1 feeds your function.

If you feed the variable name as a string, you can use globals:

a = 1

def foo(x):
    return f'{x} = {globals()[x]}'

foo('a')  # 'a = 1'

Use of global variables is advisable only for specific purposes. If the variable name is important, you can use a dictionary instead:

d = {'a': 1}

def foo(myd, x):
    return f'{x} = {myd[x]}'

foo(d, 'a')  # 'a = 1'

In most situations, the dictionary will be sufficient.

jpp
  • 159,742
  • 34
  • 281
  • 339