路径('foo')的缺点。存在()!=bool(路径('foo'))

2024-10-01 09:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

试图将我的问题重新表述为较少基于观点

当文件系统路径不存在时,pathlib.Path对象强制/计算到False有什么不利之处

例如,pathlib.Path可以使用任何__bool__逻辑编写,因为它只是一个Python类

class Path(object):
    def __init__(self, path):
        self.path_ = path

    def __bool__(self):
        return self.checkIfExistsOnFileSystemOrNot_()

    def path(self):
        return self.path_

    def checkIfExistsOnFileSystemOrNot_(self):
        # any logic here ...

    ...

我知道您可能希望构建一个python程序中不存在的文件路径,但您希望何时构建

if path:
   # do something with the path "assuming" it exits on the filesystem (and not just that it's not falsy)

我会同意的

if path.exists():
    # ...

这不是更多的努力,但考虑到我一直在两种语言之间跳跃,这给我带来了一些痛苦


Tags: thepath对象self路径returnifdef
1条回答
网友
1楼 · 发布于 2024-10-01 09:31:51

既然问题已经改变了,我在最初的回答中提出的最后一点可能是最重要的:清晰

The Zen of Python说:

Explicit is better than implicit.

Readability counts.

Path对象上显式调用.exists()是非常清楚的。一个不熟悉Python的新程序员可以阅读

if some_path.exists():
    # ...

并且可能理解它。但是

if some_path:
    # ...

更不清楚

I've been jumping around between languages this has caused me some pain.

惯用Python和惯用Ruby或C#或Scala都是不同的。没关系

现在,让我们来谈谈旧答案的其余部分:

^{}不仅仅用于表示特定可见文件系统上的文件和文件夹。它用于表示和操作路径本身(粗体添加):

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

您甚至可以在Linux系统上操作Windows样式的路径,反之亦然

将路径的真实性降低到“这个文件存在吗?”似乎是一个奇怪的设计决策。特别是当文件和目录还有其他布尔值问题时:可读吗?可写的?可执行文件?象征性的联系?目录?普通档案?先进先出

相关问题 更多 >