python - 使用 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 的方式。没有错误,但我觉得这段代码可能很奇怪。
解决方案
您应该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)
)
推荐阅读
- r - 如何在 R 中使用 qtm 将图例添加到绘图中
- reactjs - 更新状态 ReactJS 中的对象
- javascript - 单击事件不是从 reactjs 中的 select onchange 事件触发的
- react-native - Redux 操作已触发但无法导航(React-Navigation)
- mysql - 现有事务中的 Entity Framework Core 手动 sql 查询
- javascript - 为指令定义参数类型
- c# - TCP 客户端停止直到被服务器断开
- javascript - 当我删除地图中的对象时出现问题。我需要调用函数 3 次
- python - Wikipedia Dump xml文件在python中转换为文本
- python - NumPy 有像 Pandas 一样的 select_dtypes 吗?