如何在Python中组织函数(类型提示,返回,平面代码)

时间:2019-07-12 04:02:50

标签: python python-3.x

我构建了一个简单的CLI todo应用程序。它具有允许完全清除待办事项列表的功能。里面有5个语法版本。您认为哪个是最pythonic的?

def purge_tasks() -> None:
    """Deletes all tasks from the todo file."""

    # Syntax 1: initial
    confirmation = input('Are you sure you want to delete all the tasks? y/n: ')
    if confirmation.lower().startswith('y'):
        tasks = get_file_data('todo.csv', only_tasks=True)
        if tasks:
            tasks.clear()
            save_data(tasks)
            print('Todo list has been cleared.')
        else:
            print('Todo list is already empty.')

    # Syntax 2: slightly flatter
    confirmation = input('Are you sure you want to delete all the tasks? y/n: ')
    if confirmation.lower().startswith('y'):
        tasks = get_file_data('todo.csv', only_tasks=True)
        if not tasks:
            print('Todo list is already empty.')
            return None
        tasks.clear()
        save_data(tasks)
        print('Todo list has been cleared.')

    # Syntax 3: flat
    confirmation = input('Are you sure you want to delete all the tasks? y/n: ')
    if not confirmation.lower().startswith('y'):
        return None
    tasks = get_file_data('todo.csv', only_tasks=True)
    if not tasks:
        print('Todo list is already empty.')
        return None
    tasks.clear()
    save_data(tasks)
    print('Todo list has been cleared.')

    # Syntax 4: doesn't print but returns either None or str
    confirmation = input('Are you sure you want to delete all the tasks? y/n: ')
    if not confirmation.lower().startswith('y'):
        return None
    tasks = get_file_data('todo.csv', only_tasks=True)
    if not tasks:
        return 'Todo list is already empty.'
    tasks.clear()
    save_data(tasks)
    return 'Todo list has been cleared.'

    # syntax 5: slightly less flat but returns only str
    confirmation = input('Are you sure you want to delete all the tasks? y/n: ')
    if confirmation.lower().startswith('y'):
        tasks = get_file_data('todo.csv', only_tasks=True)
        if not tasks:
            return 'Todo list is already empty.'
        tasks.clear()
        save_data(tasks)
        return 'Todo list has been cleared.'

最近,我读了关于循环复杂度的知识,以及如何使代码更加扁平化是一种好习惯。所以我遇到的问题是:

  1. 我想使用类型提示,但是我不知道是否返回None 是一个好习惯,我不应该返回一个str(将print放在 消息变量并返回它)或仅按原样打印并返回bool 之后?
  2. 在此特定代码段中,我不应该返回 错了吗?
if not confirmation.lower().startswith('y'):
   return None

但是,如果我在这里返回False,那么我不应该在代码中返回True而不是None吗?否则,我将不得不导入Union来展示我可以返回False或None,但这似乎不是一个好主意。

无论如何,您认为最好的解决方法是什么?

1 个答案:

答案 0 :(得分:0)

查看代码,最好使用此代码:

def purge_tasks(s):
    if s.lower().startswith('y'):
        tasks = get_file_data('todo.csv', only_tasks=True)
        if not tasks:
            return 'Todo list is already empty.'
        tasks.clear()
        save_data(tasks)
        return 'Todo list has been cleared.'

confirmation = input('Are you sure you want to delete all the tasks? y/n:')
print(purge_tasks(confirmation))