简体   繁体   中英

How can I make this function cleaner?

The start() function is part of a simple ideabank program which can storage ideas. I woud like to make it cleaner, maybe split it for more functions.

You can call ideabank program with second argument ('--list' to list ideas or '--delete' to delete idea) and if you use '--delete' you need to provide a number for third argument (the number of idea which you want to delete). The start function handle these and exceptions. Do you have any suggestion to make start() function cleaner?

def start():
    if len(sys.argv) == 1:
        ask_for_an_idea()
    elif sys.argv[1] == "--list":
        print_ideas(read_ideas())
    elif sys.argv[1] == "--delete":
        try:
            number = int(sys.argv[2])
        except (IndexError, ValueError):
            print("Specify a number after --delete")
        else:
            try:
                delete_idea(read_ideas(), number)
            except IndexError:
                print(f"You have only {len(read_ideas())} idea(s).")
            else:
                print_ideas(read_ideas())


if __name__ == "__main__":
    start()

Something like this:

if __name__ == '__main__':
  arg_parser = argparse.ArgumentParser()
  arg_parser.add_argument('--list', help='Print ideas')
  arg_parser.add_argument('--delete', default=-1, type=int, help='Specify which idea to delete')
  arg_parser.add_argument('--store_new_idea', help='Prompt for a new idea')

  args = arg_parser.parse_args()
  if args.list is not None:
    print_ideas()
  if args.delete >= 0:
    delete_idea(args.delete)
  if args.store_new_idea is not None:
    prompt_new_idea()

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