For example:
def func(a):
# how to get the name "x"
x = 1
func(x)
If I use inspect
module I can get the stack frame object:
import inspect
def func(a):
print inspect.stack()
out:
[
(<frame object at 0x7fb973c7a988>, 'ts.py', 9, 'func', [' stack = inspect.stack()\n'], 0)
(<frame object at 0x7fb973d74c20>, 'ts.py', 18, '<module>', ['func(x)\n'], 0)
]
or use inspect.currentframe()
I can get the current frame.
But I can only get the name "a"
by inspect the function object.
Use inspect.stack
I can get the call stack:"['func(x)\n']"
,
How can I get the name of actual parameters("x"
here) when call the func
by parsing the "['func(x)\n']"
?
If I call func(x)
then I get "x"
if I call func(y)
then I get "y"
Edit:
A example:
def func(a):
# Add 1 to acttual parameter
...
x = 1
func(x)
print x # x expected to 2
y = 2
func(y)
print y # y expected to 3
use lists as references
This is my final solution. Use ast to parse the function statement and get the args.:
Out:
2 3 4
Looking at your comment explanations, the reason you are trying to do this is:
You can't do that. In python, everything is passed by value, but that value is a reference to the object you pass. Now, if that object is mutable (like a list), you can modify it, but if it's immutable, a new object is created and set. In your code example,
x
is anint
which is immutable, so if you want to change the value ofx
it, just return its new value from the function you are invoking:So what if you want to return multiple values? Use a
tuple
!That is feasible, up to a point - but nonetheless,useless in any kind of "real code". You can use it for backyard magic tricks:
Just retrieve the calling stack_frame like you are doing, then loop linearly through the variables available in the calling frame for one that references the same object you got as a parameter. The variables are in the
f_locals
andf_globals
dictionaries which are attributes of the frame object.Of course, the parameter passed may not be in a variable name to start with: it might be a constant in the caller, or it might be inside a dict or a list.
Either way, as @Nasser put it in the answer: it is not the way Python works. Objects exist in memory, and variable names, in each scope, just point to those objects. The names themselves are meaningless otherwise.