Accessing the name of an actual parameter

Chris Rebert clp2 at rebertia.com
Tue Jan 26 12:58:42 CET 2010


On Tue, Jan 26, 2010 at 3:48 AM, Hellmut Weber <mail at hellmutweber.de> wrote:
> Hi,
>
> 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?

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



More information about the Python-list mailing list