首页 > 解决方案 > 返回和检查方法执行的 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 的做法是引发异常。

任何人都可以为我提供上述方法的示例吗?

标签: python

解决方案


就个人而言,我会大大简化这一点。

在这种情况下,注释对您没有多大作用。

内存int()数据中只有两个可能的错误:

  1. ValueError- 试图转换无法转换的东西,例如int('')

  2. TypeError- 尝试转换字符串或数字类型(如int(1.23))以外的内容,例如int({'1':'2'})int(['1','2'])将是 TypeErrors。

鉴于其定义的范围,这是您应该在函数中处理的仅有的两个异常。如果您尝试处理的范围超出您准备处理的范围,那么您可能会掩盖许多其他由 Python、操作系统或调用此函数的程序部分更好地处理的异常。

在 Python 中,如果成功则返回项目也更常见,否则返回项目None。请务必明确测试is None与仅测试返回的假真伪。Noneor 0or or的返回[]False只是None isNone。(虽然你要走的路是在 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)

当然还有其他方法,例如使用装饰器用户定义的异常,但是当您有更多可能的错误要处理时,会使用这些方法。


推荐阅读