我构建了一个简单的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.'
最近,我读了关于循环复杂度的知识,以及如何使代码更加扁平化是一种好习惯。所以我遇到的问题是:
if not confirmation.lower().startswith('y'):
return None
但是,如果我在这里返回False,那么我不应该在代码中返回True而不是None吗?否则,我将不得不导入Union来展示我可以返回False或None,但这似乎不是一个好主意。
无论如何,您认为最好的解决方法是什么?
答案 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))