当前位置: 代码迷 >> python >> 如何减少python代码中的嵌套if语句
  详细解决方案

如何减少python代码中的嵌套if语句

热度:84   发布时间:2023-06-27 21:30:16.0
if flask.request.form['token'] == stored_token:
    if size_of_file > 10000:
        logging.info('data ' + filename + ' is compressed and sent')
        return gzip_compress(resp(200, data))
    else:
        logging.info(filename + ' data copy')
        return resp(200, data)
else:
    logging.info(' data ' + filename + ' is not compressed, but copied and sent')
    return resp(401, {})

我不喜欢这段代码如何帮助修复它。 或告诉我,这是一个很好的代码。

干得好:

if flask.request.form['token'] != stored_token:
    logging.info(' data ' + filename + ' is not compressed, but copied and sent')
    return resp(401, {})

if size_of_file <= 10000:
    logging.info(filename + ' data copy')
    return resp(200, data)

logging.info('data ' + filename + ' is compressed and sent')
return gzip_compress(resp(200, data))

在Google测试博客中,有描述了为什么将if语句嵌套认为错误,以及如何降低代码复杂度。