首页 > 解决方案 > 使用 try 和 catch 的最 Pythonic 方式

问题描述

def deploy_stack(region: str, props: Properties) -> Any:
   try:
        return cloudformation_resource(region).create_stack(**props)
    except botocore.exceptions.ClientError as err:
        if "AlreadyExistsException" in str(err):
            return (
                cloudformation_resource(region)
                .Stack(props["StackName"])
                .update(**props)
            )
        else:
            raise err

我想知道我的 try catch 块是否是这里最 Pythonic 的。我愿意接受建议。这对我来说更像是一种学习如何比其他任何东西都更 Pythonic 的方式。没有错误,但我觉得这段代码可能很奇怪。

标签: python

解决方案


您应该AlreadyExistsException通过默认机制捕获并让所有其他异常继续:

def deploy_stack(region: str, props: Properties) -> Any:
   try:
        return cloudformation_resource(region).create_stack(**props)
   except botocore.exceptions.AlreadyExistsException:
        return (
            cloudformation_resource(region)
            .Stack(props["StackName"])
            .update(**props)
        )

推荐阅读