简体   繁体   中英

Pythonic way of returning and checking method execution

Pythonic way of returning and checking method execution

I am currently using golang style of coding in python code, decided to move pythonic way

example:

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)

I read in python docs pythonic way of doing is raising exceptions.

Can anyone provide me example for above method?

Personally, I would simplify this greatly.

The annotations in this case are not doing much for you.

With int() you really only have two possible errors from in-memory data:

  1. ValueError - from trying to convert something that cannot be converted such as int('😀')

  2. TypeError - from trying to convert something other than a string or numeric type (like int(1.23) ) such as int({'1':'2'}) or int(['1','2']) would be TypeErrors.

These are the only two exceptions you should handle in your function given its defined scope. If you try and broadly handle more than you are prepared to handle you risk masking many other exceptions that are better handled by Python, the OS, or the part of your program that called this function.

It is also more common in Python to return the item if successful and None if not. Be sure to explicitly test is None vs just testing truth of false of the return. A return of None or 0 or [] are all False but only None is None. (Although the way you are going is seen in Python, it is not super common IMHO.)

Simplified:

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)

There are other ways of course, such using a decorator or a User Defined Exception but these are used when you have many more possible errors to deal with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM