试图将我的问题重新表述为较少基于观点
当文件系统路径不存在时,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():
# ...
这不是更多的努力,但考虑到我一直在两种语言之间跳跃,这给我带来了一些痛苦
既然问题已经改变了,我在最初的回答中提出的最后一点可能是最重要的:清晰
The Zen of Python说:
及
在
Path
对象上显式调用.exists()
是非常清楚的。一个不熟悉Python的新程序员可以阅读并且可能理解它。但是
更不清楚
惯用Python和惯用Ruby或C#或Scala都是不同的。没关系
现在,让我们来谈谈旧答案的其余部分:
^{} 不仅仅用于表示特定可见文件系统上的文件和文件夹。它用于表示和操作路径本身(粗体添加):
您甚至可以在Linux系统上操作Windows样式的路径,反之亦然
将路径的真实性降低到“这个文件存在吗?”似乎是一个奇怪的设计决策。特别是当文件和目录还有其他布尔值问题时:可读吗?可写的?可执行文件?象征性的联系?目录?普通档案?先进先出
相关问题 更多 >
编程相关推荐