【问题标题】:Almost same parameters for different function python不同功能python的参数几乎相同
【发布时间】:2022-01-27 16:02:45
【问题描述】:

例如我的代码如下:

if env = 'staging':
    db_cluster = rds.DatabaseCluster(self, 
                                     instances=2,
                                     identifier='ksdfjdsk', 
                                     region='string', 
                                     password='string',
                                     removal_policy='string'
                                     ... 
                                     ...
                                     iam='iam role name')

else:
    db_cluster = rds.DatabaseClusterFromSnapshot(self, 
                                                 instances=2,
                                                 snapshot_identifier="arn"
                                                 identifier='ksdfjdsk', 
                                                 region='string', 
                                                 password='string value',
                                                 removal_policy='stringsdfdd'
                                                 ... 
                                                 ...
                                                 iam='iam role name')

这里,DatabaseClusterDatabaseClusterFromSnapshot 是 was-cdk API。两者都采用几乎相同的参数,唯一的区别是第二个参数 snapshot_identifier 额外。

现在的问题是,是否有任何方法或逻辑可以减少 if-else 的代码块。 (因为两者都有大量的参数)

【问题讨论】:

  • 如果它们都只使用关键字参数,那么您可以使用 dict-unpacking 来调用该函数。类似于someFunc(**dict_of_values) 的东西,其中dict_of_values 类似于{"firstkw": "firstvalue", "secondkw": "secondvalue"}
  • 好的。。谢谢!我使用了 dict-unpacking...

标签: python-3.x amazon-web-services if-statement aws-cdk optional-parameters


【解决方案1】:

你可以做的一种方法是建立一个公共参数字典common_args,比如:

common_args = dict(
    instances=2,
    region="string",
    identifier="ksdfjdsk",
    password="string",
    removal_policy="string",
    iam="iam role name",
)

然后使用字典解包和dict.update (|) 将任何所需的额外参数添加到特定调用:

if env == "staging":
    db_cluster = rds.DatabaseCluster(self, **common_args)
else:
    extra_args = dict(snapshot_identifier="arn")
    db_cluster = rds.DatabaseClusterFromSnapshot(self, **(common_args | extra_args))

【讨论】:

  • 谢谢@tigs,你拯救了我的一天......再次感谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2017-12-25
  • 2023-03-26
  • 2013-10-18
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
相关资源
最近更新 更多