7

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
MaleMaldives
  • 123
  • 1
  • 1
  • 4

4 Answers4

6

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

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Tadeck
  • 132,510
  • 28
  • 152
  • 198
4

Can't be done. Python doesn't distinguish between names at that level.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • What about looping through variables using `locals()`, `globals()` and finding out which names refer to given value by comparing return values of `id()`? – Piotr Dobrogost Sep 16 '13 at 11:01
  • @PiotrDobrogost the requirement is not really coherent. There are arbitrarily many places one might want or need to look for names. – Karl Knechtel Oct 15 '22 at 06:12
3

You can do it now with the value wrapper from python-varname package.

from varname import Wrapper

fib = Wrapper(1)

def foo(arg):
  print(arg.value, arg.name)

foo(fib)
# 1, "fib"

The package is hosted at https://github.com/pwwang/python-varname

I am the author of the package. Let me know if you have any questions using it.

Panwen Wang
  • 3,573
  • 1
  • 18
  • 39
0
def print_args(**kwargs):
    for name,value in kwargs.iteritems():
        print name, value
Colin Dunklau
  • 3,001
  • 1
  • 20
  • 19