我正在研究具有很多功能的大型有限元分析代码。为了在不同函数之间传递变量,我使用了python的kwargs。我主要选择这个,这样我就可以用很多不同的方式调用这些函数,从而创造了很大的灵活性。
但是现在我正在处理一个问题。从主函数我使用kwargs调用另一个函数。然后,第二个函数处理输入并添加新的kwargs。问题是在第一个中无法访问在该函数中创建的新kwargs。有这样做的pythonic方式吗?我创建了以下代码作为示例:
# Create main function
def main(**kwargs):
# Add a key word argument
kwargs["textMain"] = "text added in main"
# Call a function with existing kwargs and a new one
functionA(textNew = "text added in new" ,**kwargs)
# Test what is in kwargs after subfunction is called
print("\nTest kwargs after subfunction is called:")
if "textMain" in kwargs:
print(kwargs["textMain"])
if "textNew" in kwargs:
print(kwargs["textNew"])
if "textA" in kwargs:
print(kwargs["textA"])
def functionA(**kwargs):
# Test kwargs before adding kwargs in subfunction
print("\nTest kwargs in subfunction before adding:")
if "textMain" in kwargs:
print(kwargs["textMain"])
if "textNew" in kwargs:
print(kwargs["textNew"])
if "textA" in kwargs:
print(kwargs["textA"])
# Add kwargs
kwargs["textA"] = "text added in sub A"
# and test kwargs again
print("\nTest kwargs in subfunction after adding:")
if "textMain" in kwargs:
print(kwargs["textMain"])
if "textNew" in kwargs:
print(kwargs["textNew"])
if "textA" in kwargs:
print(kwargs["textA"])
if __name__ == "__main__":
main()
这会产生以下输出:
#Test kwargs in subfunction before adding:
#text added in main
#text added in new
#Test kwargs in subfunction after adding:
#text added in main
#text added in new
#text added in sub A
#Test kwargs after subfunction is called:
#text added in main
我喜欢的输出是:
#Test kwargs in subfunction before adding:
#text added in main
#text added in new
#Test kwargs in subfunction after adding:
#text added in main
#text added in new
#text added in sub A
#Test kwargs after subfunction is called:
#text added in main
#text added in new
#text added in sub A
如果任何人能解决我的问题,那将是非常有帮助的。提前谢谢!
答案 0 :(得分:2)
在调用表达式中使用**kwargs
语法时,Python会扩展字典并传入单独的参数。然后,函数签名中的相同语法告诉Python在该函数中创建 new 字典以捕获关键字参数。
换句话说,kwargs
中的main()
与functionA()
中的字典不是同一个字典。
传入实际字典(不使用**kwargs
语法)或让functionA()
返回新字典。
作为单个参数传入kwargs
,您可以从functionA()
更改字典,并查看main()
中反映的更改,因为它们现在共享对同一字典的引用:
def main(**kwargs):
functionA(kwargs, textNew="text added in new")
# ... etc ...
def functionA(mapping, **kwargs):
# do something with mapping, it is the same dictionary as kwargs in main
从kwargs
返回更新的functionA()
字典要求您将新对象重新分配回kwargs
中的main()
:
def main(**kwargs):
kwargs = functionA(textNew="text added in new", **kwargs)
# ... etc ...
def functionA(**kwargs):
# ...
return kwargs