consider the following piece of code, please
----- -----
def f(param):
nameOfParam = ???
# here I want to access the name of the variable
# which was given as parameter to the function
print nameOfParam, param
return
if __name__ == __main__:
a = 1
f(a)
b = 'abcd'
f(a)
----- -----
The output should be:
'a' 1
'b' 'abcd'
----- -----
I tried to look at globals() and locals(), gave a look to the frames
(sys._getframe(0) and sys._getframe(1),
but did not see a possibility to access the information a want
How can this be done?
TIA
Hellmut
--
Dr. Hellmut Weber ma...@hellmutweber.de
Degenfeldstraße 2 tel +49-89-3081172
D-80803 München-Schwabing mobil +49-172-8450321
please: No DOCs, no PPTs. why: tinyurl.com/cbgq
It's an FAQ that's not in the FAQ. The popular answer is "Don't try to
do that! There's usually a less magic way to accomplish your goal.".
Alternatives can usually be proffered if the exact use case is
explained specifically.
Cheers,
Chris
--
http://blog.rebertia.com
Not in any efficient way. A debugger can do it, and you can do it in the same
way as a debugger, checking stack frames and the source code. But if it's
debugging that you're after then use a debugger -- that's what they're for.
Otherwise, just change the way that you invoke the routine.
For example,
>>> def f( **kwa ):
... print( kwa )
...
>>> a = 1234
>>> b = "huh"
>>> f( a = a, b = b )
{'a': 1234, 'b': 'huh'}
>>> _
Cheers & hth.,
- Alf
Tell us whant you want to achieve precisely with the parameter names,
maybe we'll find something suitable.
JM
It's naive to think this question even makes sense. There are many ways
f can be called which don't involve a parameter:
f(42)
f(time())
f(a+123)
f(sin(a))
f(f(1))
and so on.
Cheers,
Gary Herron
> It's naive to think this question even makes sense. There are many ways
> f can be called which don't involve a parameter:
>
> f(42)
> f(time())
> f(a+123)
> f(sin(a))
> f(f(1))
>
> and so on.
So long as the OP doesn't care if they get no names or several name that
might not matter. However, explicitly passing in the name you want to use
is likely to be more useful.
>>> def getcallersnames(obj):
f = inspect.currentframe().f_back.f_back
return [name for name in f.f_locals if f.f_locals[name] is obj]
>>> def bip(x):
print getcallersnames(x)
>>> def foo(bar):
baz = bar
bip(baz)
bip(baz+1)
>>> foo(3)
['bar', 'baz']
[]
>>> bip(bip)
['bip']
--
Duncan Booth http://kupuguy.blogspot.com
Another issue:
class Foo:
test = 'test'
def foo(bar):
bip(bar.test)
f = Foo()
foo(f)
[]
That restricts pretty much the use of getcallersnames.
As said before, there is hardly any legit design which would require to
know the actual refrence used to pass a parameter.
JM