Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python obtain variable name of argument in a function

I want to do something like this:

fib = 1
foo = (arg):
    print arg, argName # the name of the variable that was put in for arg
foo(fib)

And get this returned:

1, fib
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot do it like that (as Ignacio Vazquez-Abrams already answered), but you can do it in a similar way:

>>> def foo(**kwargs):
    for arg_name in kwargs:
        return kwargs[arg_name], arg_name


>>> foo(fib=1)
(1, 'fib')

The only difference is that you must use keyword arguments, otherwise it will not work.

The alternative solution is also to access __name__ attribute of passed variable, which will result in obtaining the name of function, class or name (or anything else that will have this name defined). The only thing that you should be aware of, is that by default this is not the name of the variable, but the original name of the function/class/module (the one assigned when it was being defined). See the example here: http://ideone.com/MzHNND


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...