Getting external name of passed variable

faulkner faulkner612 at comcast.net
Wed Jun 21 01:32:00 CEST 2006


>>> import sys
>>> tellme = lambda x: [k for k, v in sys._getframe(1).f_locals.iteritems() if v == x]
>>> a=1
>>> tellme(a)
['a']

Michael Spencer wrote:
> David Hirschfield wrote:
> > I'm not sure this is possible, but it sure would help me if I could do it.
> >
> > Can a function learn the name of the variable that the caller used to
> > pass it a value? For example:
> >
> > def test(x):
> >   print x
> >
> > val = 100
> > test(val)
> >
> > Is it possible for function "test()" to find out that the variable it is
> > passed, "x", was called "val" by the caller?
> > Some kind of stack inspection?
>
> Perhaps, but don't try it ;-)
> >
> > Any help greatly appreciated,
> > -David
> >
> Can't you use keyword arguments?
>
>  >>> def test(**kw):
> ...     print kw
> ...
>  >>> test(val=3)
> {'val': 3}
>  >>> test(val=3, otherval = 4)
> {'otherval': 4, 'val': 3}
>  >>>
> 
> Michael




More information about the Python-list mailing list