处理异常或返回值的更好方法

时间:2014-12-09 01:03:15

标签: python

def foo(directory):
    filename = '' #dont like this
    all_files = [get from somewhere]
    try:
        if 'foo' in all_files:
            filename = 'foo'

        else:
            filename = all_files[0]
     except ValueError:
          logger.warning('Directory is empty')
     finally:
             return os.path.join(directory, filename)

所以,这就是我到目前为止所拥有的...... 有没有更好的方法来处理这个...我们要么返回一个值还是记录错误..?

2 个答案:

答案 0 :(得分:3)

更容易乞求宽恕而不是请求许可。您可以对filename变量使用条件分配,如果这是假的,那么您可以围绕它发出警告。

根据您真正想要完成的内容,您可以使用all_files的长度来查看该目录是否真的为空。

def foo(directory):
    all_files = [get from somewhere] or []

    if len(all_files) == 0:
        logger.warning('Directory is empty')
        return ''
    else:
        filename = 'foo' if 'foo' in all_files else all_files[0]       
        return os.path.join(directory, filename)

答案 1 :(得分:2)

def foo(directory):
    all_files = [get from somewhere]
    try:
        filename = 'foo' if 'foo' in all_files else all_files[0]
    except (IndexError,ValueError):
        logger.warning('Directory is empty')
    else:
        return os.path.join(directory, filename)

可能更好......