【问题标题】:How to organize a function in Python (type hints, return, flat code)如何在 Python 中组织函数(类型提示、返回、平面代码)
【发布时间】:2019-11-21 19:30:17
【问题描述】:

我构建了一个简单的 CLI 待办事项应用程序。它具有允许完全清除待办事项列表的功能。里面有 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 放在一个 message 变量并返回它)或按原样打印并返回 bool 之后呢?
  2. 在这个特殊的代码 sn-p 中,我不应该返回吗 假的?
if not confirmation.lower().startswith('y'):
   return None

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

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

【问题讨论】:

  • 欢迎来到 Stack Overflow Patrick!在您的第二个实现中,如果您的任务为空,即当您只需要打印print('Todo list is already empty.') 时,将打印print('Todo list is already empty.')print('Todo list has been cleared.'),语法相同:3
  • 谢谢。是的,我想我已经修补了它。
  • 您希望将所有修改任务列表的代码移动到单独的函数(或类)中,而不是主流程的一部分。当您将用户交互与逻辑代码混合使用时,编写单元测试会变得很困难。至于退货,您无需使用return None,只需退货即可(如果您什么都不退货,则与return None 相同)。我将创建一个可以加载/安全任务并具有操作方法的任务类。
  • 这是有道理的。虽然我还没有学会如何进行测试,但我可以看到用户输入是如何阻碍的。回报小费表示赞赏。

标签: python python-3.x


【解决方案1】:

看代码最好用这个:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 2017-04-03
    • 2018-08-10
    • 2014-03-06
    • 2021-02-17
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多