How to improve code clarity in nested try-except-else clauses?

后端 未结 3 750
庸人自扰
庸人自扰 2021-01-20 05:19

Sometimes I have a cascade of different things I can try to accomplish a task, e. g. If I need to get a record I can first try to find the record, and if this fails, I can c

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 05:29

    You could break that into multiple functions ?

    def handle_missing():
        try:
            record = create_record()
        except CreateFailed:
            record = tape
            logger.info("Using a tape now")
        else:
            logger.info("Created a new record")
        return record
    
    
    def get_record():
        try:
            record = find_record()
        except NoSuchRecord:
            record = handle_missing()
        else:
            logger.info("Record found")
        return record
    

    And then you'd use it like,

    record = get_record()
    

提交回复
热议问题