在Python函数中,有没有办法在调用者端告诉参数的变量名?

时间:2015-07-29 01:59:19

标签: python function namespaces

我正在尝试创建记录器功能:

def logger(someVariable): 
    # some code that prints the name of someVariable 

所以当我调用函数时:

logger(myvarA)        # should output the string 'myvarA'
logger(someobj.varB)  # should output the string 'someobj.varB'
logger(myarr[3])      # should (probably) output 'myarr[3]'

不确定是否所有或甚至任何一种情况都可能发生?用例是在iPython Notebook中有一个简单的函数来记录它们的值的任何变量,而不必输入如下所示:

logger(myVarA,'myVarA')
logger(myarr[i],'myarr[{}]'.format(i))

1 个答案:

答案 0 :(得分:1)

检查模块(https://docs.python.org/3/library/inspect.html#inspect.getframeinfo)也会为您提供代码上下文。您只需要解析它以获取传递的内容的文本。只有一个变量,它很容易做到。这是一个样本。

std::unique_ptr

输出

import inspect
import re

def handle_nested_parens(v):
   parens = 0
   output = ""
   for c in v:
       if c == ")":
           parens = parens - 1
           if parens < 0:
               return output
       output += c
       if c == "(":
           parens = parens + 1
   return output

def logger(v):
   currentframe = inspect.currentframe()
   code_context = inspect.getouterframes(currentframe,1)[1][4][0]
   variable = handle_nested_parens(re.sub(r".*logger\((.*)",r"\1", code_context))
   print("{0} => {1}".format(variable, v))


def testing(a):
   return(a)

def submain(a):
   ab = (1, 2, a)
   logger(testing(ab))
   return 15

def main():
   xyz = "hello"
   logger(xyz)
   logger(submain(xyz))


if __name__ == '__main__':
    a = 5
    logger(a)
    main()