[英]Python, how to pass arbitrary variables from function to function in the most elegant way?
I have a dictionary vars = {'a': 1, 'b': 2}
with key/value pairs.我有一个带有键/值对的字典
vars = {'a': 1, 'b': 2}
。 This dictionary can be extended with new variables in the future.将来可以使用新变量扩展该字典。 I would like to call func1 with variables from vars dict.
我想用 vars dict 中的变量调用 func1。 In func1 I will use zero or more variables from vars dict.
在 func1 中,我将使用 vars dict 中的零个或多个变量。 If func1 has to call func2, I would like func2 to receive all variables from original vars dict.
如果 func1 必须调用 func2,我希望 func2 从原始 vars dict 接收所有变量。 Func2 will use zero or more variables from vars dict.
Func2 将使用 vars dict 中的零个或多个变量。
Something like this:像这样的东西:
def func1(**kwargs):
print(f'func1 a = {a}, b is not important')
return func2(**kwargs)
def func2(**kwargs):
return f'func2 a = {a}, b = {b}, both variables are important'
vars = {'a' : 1, 'b' : 2}
print(func1(**vars))
But this doesn't work because kwargs is a dictionary.但这不起作用,因为 kwargs 是一本字典。 I can unpack variables at the beginning of the function if needed as:
如果需要,我可以在 function 开头解压缩变量:
a = kwargs['a']
b = kwargs['b']
but if a new variable "c" shows up in original vars dictionary, I will have to change these unpackings at the beginning of the each function.但是如果原始变量字典中出现了一个新变量“c”,我将不得不在每个 function 的开头更改这些解包。 I could also set parameters
def func1(a, b):
and def func2(a, b):
but i have to recreate kwargs dict in order to send it further down.我还可以设置参数
def func1(a, b):
和def func2(a, b):
但我必须重新创建 kwargs dict 才能将其进一步发送。 Again, if a new variable "c" shows up, I will have to change signature of each function.同样,如果出现新变量“c”,我将不得不更改每个 function 的签名。 I could also define func1 as bellow in order pass variable a further down:
我还可以将 func1 定义为波纹管,以便进一步向下传递变量:
def func1(a, kwargs):
print(f'func1 a = {a}, b is not important')
kwargs['a'] = a
return func2(**kwargs)
Maybe to create an object and to set its properties as vars dict key/value pairs, and than send this object as function's parameter?也许要创建一个 object 并将其属性设置为 vars dict 键/值对,然后将此 object 作为函数参数发送?
How to pass arbitrary variables from function to function in the most elegant way in this scenario?在这种情况下,如何以最优雅的方式将任意变量从 function 传递到 function?
Regards.问候。
Why not just keep the variables in the dictionary and access them that way?为什么不将变量保存在字典中并以这种方式访问它们呢?
def func1(**kwargs):
print(f"func1 a = {kwargs['a']}, b is not important")
return func2(**kwargs)
def func2(**kwargs):
return f"func2 a = {kwargs['a']}, b = {kwargs['b']}, both variables are important"
vars = {'a' : 1, 'b' : 2}
print(func1(**vars))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.