python - 返回和检查方法执行的 Pythonic 方式
问题描述
返回和检查方法执行的 Pythonic 方式
我目前在python代码中使用golang风格的编码,决定移动pythonic方式
例子:
import sys
from typing import Union, Tuple
def get_int_list(list_data: list) -> Tuple[Union[list, None], bool]:
try:
return [int(element) for element in list_data], True
except ValueError:
print("Failed to convert int elements list")
return None, False
my_list = ["1", "2", "a"]
int_list, status = get_int_list(my_list)
if not status:
sys.exit(1)
sys.exit(0)
我在 python 文档中读到 pythonic 的做法是引发异常。
任何人都可以为我提供上述方法的示例吗?
解决方案
就个人而言,我会大大简化这一点。
在这种情况下,注释对您没有多大作用。
内存int()
数据中只有两个可能的错误:
ValueError
- 试图转换无法转换的东西,例如int('')
TypeError
- 尝试转换字符串或数字类型(如int(1.23)
)以外的内容,例如int({'1':'2'})
或int(['1','2'])
将是 TypeErrors。
鉴于其定义的范围,这是您应该在函数中处理的仅有的两个异常。如果您尝试处理的范围超出您准备处理的范围,那么您可能会掩盖许多其他由 Python、操作系统或调用此函数的程序部分更好地处理的异常。
在 Python 中,如果成功则返回项目也更常见,否则返回项目None
。请务必明确测试is None
与仅测试返回的假真伪。None
or 0
or or的返回[]
都False
只是None
is
None。(虽然你要走的路是在 Python 中看到的,但恕我直言,这不是超级常见的。)
简化:
import sys
def get_int_list(list_data):
try:
return [int(element) for element in list_data]
# limit 'except' to:
# 1) What is a likely exception in THIS function directly from 'try' and
# 2) what you are prepared to handle
# Other exceptions should be handled by caller, Python or OS
except (ValueError, TypeError) as e:
print("Failed to convert int elements list")
print(e)
# options now are:
# 1) return None
# 2) return []
# 3) exit program here
# 4) set a flag by returning a consistent data structure or object
# which you choose is based on how the function is called
return None
# you would handle Exceptions building the list HERE - not in the function
my_list = ["1", "2", "3"]
nums=get_int_list(my_list)
if nums is None:
# failure -- exit
sys.exit(1)
#success
print(nums)
sys.exit(0)
推荐阅读
- powershell - PowerShell脚本使用扩展名查找文件并排除文件夹
- php - phpredis zRange 返回
- c# - 使用 ASP.Net Core 2.0 C# 在 MongoDB 中插入实时数据
- r - 在包函数中使用 data.table 失败
- ruby - Protobuf 解析文本
- ios - 警告“将架构 arm64 映射到 x86_64”是什么意思?
- angular - 如何将购买的主题合并到 Angular 6 + Bootstrap 4 应用程序中
- sql-server-2008 - 在 SQL Server 2008 中使用命名空间解析 XML
- java - 通过通知最后一次交换发生的位置来改进冒泡排序
- node.js - 我可以在不要求客户在其浏览器中使用安全例外的情况下将 https 节点服务器部署到客户的计算机吗?