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
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
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.