python obtain variable name of argument in a function

前端 未结 4 1275
你的背包
你的背包 2020-12-04 00:04

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)

A

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 00:05

    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.

提交回复
热议问题