首页 > 解决方案 > 是否有任何 PEP 指定新代码是否应该与 Python 2 兼容?

问题描述

使以下代码与 Python 2 兼容就像删除函数定义末尾的返回 ( -> None) 一样简单。

import csv
fieldnames = ['this', 'is', 'unimportant', 'spam', 'eggs']
def create_log_file(fname) -> None:
    """ If log file exists, does nothing, else creates log file

    Arguments:
        fname {str} -- The name of the log file
    """
    try:
        f = open(fname, "r")
        f.close()
    except IOError:
        with open(fname, "w") as f:
            writer = csv.DictWriter(f, fieldnames)
            writer.writeheader()

是让它向后兼容更可取,还是我们应该尽可能明确,因为 Python 3 允许我们这样做(在这种情况下,我也可以删除该IOError or部分)?

还是“Python 2 兼容性”与“显式优于隐式”只是个人喜好问题?

标签: pythonpython-3.xpython-2.x

解决方案


推荐阅读