Python 如何获取传递给函数的变量的原始变量名
是否可以获取传递给函数的变量的原始变量名?例如Python 如何获取传递给函数的变量的原始变量名,python,function,variables,Python,Function,Variables,是否可以获取传递给函数的变量的原始变量名?例如 foobar = "foo" def func(var): print var.origname 以便: func(foobar) 返回: >foobar 编辑: 我只想做一个函数,比如: def log(soup): f = open(varname+'.html', 'w') print >>f, soup.prettify() f.close() 。。并让函数根据传递给它的变量名生成文件名
foobar = "foo"
def func(var):
print var.origname
以便:
func(foobar)
返回:
>foobar
编辑:
我只想做一个函数,比如:
def log(soup):
f = open(varname+'.html', 'w')
print >>f, soup.prettify()
f.close()
。。并让函数根据传递给它的变量名生成文件名
我想如果不可能的话,我每次只能将变量和变量名作为字符串传递。你不能。在传递给函数之前对其进行求值。您所能做的就是将其作为字符串传递。如果您想要键值对关系,也许使用字典会更好
…或者,如果您试图从代码中创建一些自动文档,也许像Doxygen()这样的东西可以帮您完成这项工作?编辑:为了清楚起见,我不建议您使用它,它会崩溃,会很混乱,对您没有任何帮助,但它可以用于娱乐/教育目的 您可以使用
inspect
模块进行黑客攻击,我不建议这样做,但您可以这样做
import inspect
def foo(a, f, b):
frame = inspect.currentframe()
frame = inspect.getouterframes(frame)[1]
string = inspect.getframeinfo(frame[0]).code_context[0].strip()
args = string[string.find('(') + 1:-1].split(',')
names = []
for i in args:
if i.find('=') != -1:
names.append(i.split('=')[1].strip())
else:
names.append(i)
print names
def main():
e = 1
c = 2
foo(e, 1000, b = c)
main()
输出:
['e', '1000', 'c']
s
i = 1
f = 2.0
s = string
dct['key'] = value
obj.value = 42
看起来Ivo比我先检查了
inspect
,但这里有另一个实现:
import inspect
def varName(var):
lcls = inspect.stack()[2][0].f_locals
for name in lcls:
if id(var) == id(lcls[name]):
return name
return None
def foo(x=None):
lcl='not me'
return varName(x)
def bar():
lcl = 'hi'
return foo(lcl)
bar()
# 'lcl'
当然,它也可能被愚弄:
def baz():
lcl = 'hi'
x='hi'
return foo(lcl)
baz()
# 'x'
寓意:不要这样做。如果您知道调用代码的样子,您可以尝试的另一种方法是使用:
code
将包含用于调用func
的代码行(在您的示例中,它将是字符串func(foobar)
)。您可以解析它以提取参数添加到Michael Mrozek的答案中,您可以通过以下方式提取与完整代码相对应的精确参数:
import re
import traceback
def func(var):
stack = traceback.extract_stack()
filename, lineno, function_name, code = stack[-2]
vars_name = re.compile(r'\((.*?)\).*$').search(code).groups()[0]
print vars_name
return
foobar = "foo"
func(foobar)
# PRINTS: foobar
@Ivo Wetzel的答案适用于在一行中进行函数调用的情况,如
e = 1 + 7
c = 3
foo(e, 100, b=c)
如果函数调用不在一行中,如:
e = 1 + 7
c = 3
foo(e,
1000,
b = c)
以下代码工作:
import inspect, ast
def foo(a, f, b):
frame = inspect.currentframe()
frame = inspect.getouterframes(frame)[1]
string = inspect.findsource(frame[0])[0]
nodes = ast.parse(''.join(string))
i_expr = -1
for (i, node) in enumerate(nodes.body):
if hasattr(node, 'value') and isinstance(node.value, ast.Call)
and hasattr(node.value.func, 'id') and node.value.func.id == 'foo' # Here goes name of the function:
i_expr = i
break
i_expr_next = min(i_expr + 1, len(nodes.body)-1)
lineno_start = nodes.body[i_expr].lineno
lineno_end = nodes.body[i_expr_next].lineno if i_expr_next != i_expr else len(string)
str_func_call = ''.join([i.strip() for i in string[lineno_start - 1: lineno_end]])
params = str_func_call[str_func_call.find('(') + 1:-1].split(',')
print(params)
您将获得:
[u'e', u'1000', u'b = c']
但是,这仍然可能会中断。因为您可以有多个具有相同内容的变量,而不是传递变量(内容),所以在字符串中传递它的名称并从调用者堆栈框架中的本地词典中获取变量内容可能会更安全(并且会更简单)
def displayvar(name):
import sys
return name+" = "+repr(sys._getframe(1).f_locals[name])
为了实现繁荣,这里有一些我为这项任务编写的代码,一般来说,我认为Python中缺少一个模块,可以让每个人都对调用方环境进行良好而健壮的检查。与rlang eval框架在R中提供的类似
import re, inspect, ast
#Convoluted frame stack walk and source scrape to get what the calling statement to a function looked like.
#Specifically return the name of the variable passed as parameter found at position pos in the parameter list.
def _caller_param_name(pos):
#The parameter name to return
param = None
#Get the frame object for this function call
thisframe = inspect.currentframe()
try:
#Get the parent calling frames details
frames = inspect.getouterframes(thisframe)
#Function this function was just called from that we wish to find the calling parameter name for
function = frames[1][3]
#Get all the details of where the calling statement was
frame,filename,line_number,function_name,source,source_index = frames[2]
#Read in the source file in the parent calling frame upto where the call was made
with open(filename) as source_file:
head=[source_file.next() for x in xrange(line_number)]
source_file.close()
#Build all lines of the calling statement, this deals with when a function is called with parameters listed on each line
lines = []
#Compile a regex for matching the start of the function being called
regex = re.compile(r'\.?\s*%s\s*\(' % (function))
#Work backwards from the parent calling frame line number until we see the start of the calling statement (usually the same line!!!)
for line in reversed(head):
lines.append(line.strip())
if re.search(regex, line):
break
#Put the lines we have groked back into sourcefile order rather than reverse order
lines.reverse()
#Join all the lines that were part of the calling statement
call = "".join(lines)
#Grab the parameter list from the calling statement for the function we were called from
match = re.search('\.?\s*%s\s*\((.*)\)' % (function), call)
paramlist = match.group(1)
#If the function was called with no parameters raise an exception
if paramlist == "":
raise LookupError("Function called with no parameters.")
#Use the Python abstract syntax tree parser to create a parsed form of the function parameter list 'Name' nodes are variable names
parameter = ast.parse(paramlist).body[0].value
#If there were multiple parameters get the positional requested
if type(parameter).__name__ == 'Tuple':
#If we asked for a parameter outside of what was passed complain
if pos >= len(parameter.elts):
raise LookupError("The function call did not have a parameter at postion %s" % pos)
parameter = parameter.elts[pos]
#If there was only a single parameter and another was requested raise an exception
elif pos != 0:
raise LookupError("There was only a single calling parameter found. Parameter indices start at 0.")
#If the parameter was the name of a variable we can use it otherwise pass back None
if type(parameter).__name__ == 'Name':
param = parameter.id
finally:
#Remove the frame reference to prevent cyclic references screwing the garbage collector
del thisframe
#Return the parameter name we found
return param
如果您希望在不使用源文件(即来自Jupyter Notebook)的情况下获得应答中的调用者参数,则此代码(组合自)将起作用(至少在一些简单的情况下):
def get_caller_params():
#获取此函数调用的帧对象
thisframe=inspect.currentframe()
#获取父调用帧的详细信息
frames=inspect.getouterframes(thisframe)
#帧0是此函数的帧
#帧1是调用方函数的帧(我们要检查的帧)
#帧2是调用调用方的代码的帧
调用方函数名称=帧[1][3]
调用的代码\u调用方=inspect.findsource(帧[2][0])[0]
#解析代码以获取调用的抽象语法树的节点
nodes=ast.parse(“”.join(调用调用方的代码))
#查找调用该函数的节点
i_expr=-1
对于枚举(nodes.body)中的(i,node):
如果节点是我们的函数调用(节点、调用方函数名):
i_expr=i
打破
#与呼叫开始连接
idx_start=nodes.body[i_expr].lineno-1
#在通话结束时排队
如果i_expr
然后可以按如下方式运行:
def测试(*par_值):
par_names=get_caller_params()
对于名称,邮政编码中的val(par_名称,par_值):
打印(名称、val)
a=1
b=2
字符串='text'
测试(a,b,
一串
)
要获得所需的输出:
a 1
b 2
string text
您可以使用pythonvarname包
from varname import nameof
s = 'Hey!'
print (nameof(s))
输出:
['e', '1000', 'c']
s
i = 1
f = 2.0
s = string
dct['key'] = value
obj.value = 42
套餐如下:
我想知道如何解决这个问题。因此我研究并提出了以下(稍微简化的)解决方案。它可能不是100%防弹的(例如,我放弃了使用缩进获取文本,我假设只有一个函数参数),但它适用于不同的测试用例。它不需要解析源代码本身,因此它应该比以前的解决方案更健壮、更简单
#!/usr/bin/env python3
import inspect
from executing import Source
def func(var):
callFrame = inspect.currentframe().f_back
callNode = Source.executing(callFrame).node
source = Source.for_frame(callFrame)
expression = source.asttokens().get_text(callNode.args[0])
print(expression, '=', var)
i = 1
f = 2.0
dct = {'key': 'value'}
obj = type('', (), {'value': 42})
func(i)
func(f)
func(s)
func(dct['key'])
func(obj.value)
输出:
['e', '1000', 'c']
s
i = 1
f = 2.0
s = string
dct['key'] = value
obj.value = 42
更新:如果你想将“魔法”移动到一个单独的功能中,你只需再向后移动一帧,再加上一个f\u back
def get_name_of_argument():
callFrame = inspect.currentframe().f_back.f_back
callNode = Source.executing(callFrame).node
source = Source.for_frame(callFrame)
return source.asttokens().get_text(callNode.args[0])
def func(var):
print(get_name_of_argument(), '=', var)
不。也许如果你描述一下你在更高层次上想要实现的目标,我们可以给你一些建议或其他解决方案?我主要想知道你为什么想要它?好吧,这是不可能的,以前从来没有听说过有人想要这样做。相关:那么有没有一种方法可以获取变量并将其名称保存为字符串?你可以访问locals()
和globals()
字典,查找与值匹配的变量,但这确实不雅观。最好只需手动传递它:log('myvar',myvar)
。这是一个