Python 根据条件向函数传递不同的参数名称
我的代码需要一种方法来确定应该传递给API函数的两个参数名称中的哪一个不是值。有两个可能的变量名,调用中将只使用其中一个。类似这样的元代码:Python 根据条件向函数传递不同的参数名称,python,function,variables,lambda,Python,Function,Variables,Lambda,我的代码需要一种方法来确定应该传递给API函数的两个参数名称中的哪一个不是值。有两个可能的变量名,调用中将只使用其中一个。类似这样的元代码: user_input = 'tgw-xxxx' if user_input == 'tgw-xxxx': <gateway = (TransitGateway=user_input)> else: <gateway = (VpnGateway=user_input)> some_api_call( Cust
user_input = 'tgw-xxxx'
if user_input == 'tgw-xxxx':
<gateway = (TransitGateway=user_input)>
else:
<gateway = (VpnGateway=user_input)>
some_api_call(
CustomerGatewayId='blah',
BgpAsn=65000,
<gateway> # pass either `TransitGateway` argument
# or `VpnGateway` argument
)
因此,换句话说,API在这里只接受TransitGateway或VpnGateway变量,但不同时接受这两个变量
你知道解决这个问题的最好方法吗?谢谢 查看Python文档中的to函数。基本上,您需要创建一个字典来保存您的值:
user_input = 'tgw-xxxx'
args = {}
if user_input == 'tgw-xxxx':
args['TransitGateway'] = user_input
else:
args['VpnGateway'] = user_input
然后,您可以将该字典解压缩到函数的参数中:
some_api_call(
CustomerGatewayId='blah',
BgpAsn=65000,
**args
)
这将根据args中的值调用一些_api_call…、TransitGateway='something'或一些_api_call…、VpnGateway='other'。而不是在两个条件分支中设置变量,您可以在每个分支中使用不同的参数调用api:
if user_input == 'tgw-xxxx':
some_api_call(
CustomerGatewayId='blah',
BgpAsn=65000,
TransitGateway=user_input
)
else:
some_api_call(
CustomerGatewayId='blah',
BgpAsn=65000,
VpnGateway=user_input,
)
如果必须只进行一次调用,请将所有关键字参数放入字典,并在条件中设置不同的网关:
params = {
CustomerGatewayId='blah',
BgpAsn=65000,
}
if user_input == 'tgw-xxxx':
params['TransitGateway'] = user_input
else:
params['VpnGateway'] = user_input
然后,可以使用“double splat”命令传递所有参数:
some_api_call(**params)