【问题标题】:Handling Nonetype for setting a path处理 Nonetype 以设置路径
【发布时间】:2020-04-21 09:35:48
【问题描述】:

我有以下一段代码,我一直在思考如何更简洁地编写它。在下面的行中,我有一个名为 export_path 的变量,它可能由用户给出,也可能不给出,如果给出,生成的文件将被导出到该文件夹​​。但是,如果是None,则文件将导出到 CWD。

if export_path is not None:
    export_directory = export_path + f'/{project_name}'
    with open(export_directory, 'w') as file:
        file.write(text)
else:
    with open(f'{project_name}', 'w') as file:
        file.write(text)

我的问题是,我想避免这个 if/else 块并让它更干净。到目前为止,我的主要斗争是关于如何处理变量 export_path 时没有。理想情况下,我想做这样的事情:

export_directory = export_path + f'/{project_name}'
with open(export_directory, 'w') as file:
     file.write(text)

如果export_pathNone,那么只会导出到 CWD。但是,这里的问题是,显然您不能将 Nonetype 和字符串相加。所以我的问题来了,它以某种方式处理这个Nonetype,以便可以创建一条单线路径?

【问题讨论】:

    标签: python dry


    【解决方案1】:

    你在寻找这样的东西吗?

    exp_directory = export_path if export_path is not None else f"{project_name}"
    

    【讨论】:

    • f"{project_name}" if export_path is None else export_path(避免否定 - 积极的断言通常需要较少的认知费用)。
    • 无论你的船漂浮在哪里@brunodesthuilliers!我更喜欢我的方式,因为它对我来说更像是一个句子
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多