Skip to main content
 首页 » 编程设计

python之pathlib.path 允许除了 string 和 Path 之外的其他类型加入

2024年10月17日8jiqing9006

如何更改 pathlib.Path._parse_args,这样我就不能只有其他类型(如 LocalPath)作为 Path 的参数还可以使用其他类型作为基于 / 的连接等的参数吗?

from pathlib import Path 
Path(tmplib) / 25 / True 

使用 tmplib 来自 py._path.local 的 LocalPath,其他的自动转换为它们的 str()表示?

我尝试了子类化和猴子修补,如这个 ( pathlib Path and py.test LocalPath ) 问题中所示,但这没有用。

Path 看起来很难扩展。

请您参考如下方法:

pathlib(和 pathlib2 用于 Python 版本 < 3.4)主要由四个与路径直接相关的类组成 Path、PosixPath、WindowsPath 和 PurePath(pathlib2 中的 BasePath)。如果您对其中的每一个进行子类化,并按照以下方式复制和调整 Path.__new__() 和 PurePath._parse_args() 的代码:

import os 
import sys 
if sys.version_info < (3, 4): 
    import pathlib2 as pathlib 
else: 
    import pathlib 
 
 
class PurePath(pathlib.Path): 
    __slots__ = () 
    types_to_stringify = [int] 
 
    @classmethod 
    def _parse_args(cls, args): 
        # This is useful when you don't want to create an instance, just 
        # canonicalize some constructor arguments. 
        parts = [] 
        for a in args: 
            if isinstance(a, pathlib.PurePath): 
                parts += a._parts 
            elif sys.version_info < (3,) and isinstance(a, basestring): 
                # Force-cast str subclasses to str (issue #21127) 
                parts.append(str(a)) 
            elif sys.version_info >= (3, 4) and isinstance(a, str): 
                # Force-cast str subclasses to str (issue #21127) 
                parts.append(str(a)) 
            elif isinstance(a, tuple(PurePath.types_to_stringify)): 
                parts.append(str(a)) 
            else: 
                try: 
                    parts.append(a) 
                except: 
                    raise TypeError( 
                        "argument should be a path or str object, not %r" 
                        % type(a)) 
        return cls._flavour.parse_parts(parts) 
 
 
class WindowsPath(PurePath, pathlib.PureWindowsPath): 
    __slots__ = () 
 
 
class PosixPath(PurePath, pathlib.PurePosixPath): 
    __slots__ = () 
 
 
class Path(pathlib.Path): 
    __slots__ = () 
 
    def __new__(cls, *args, **kwargs): 
        if cls is Path: 
            cls = WindowsPath if os.name == 'nt' else PosixPath 
        self = cls._from_parts(args, init=False) 
        if not self._flavour.is_supported: 
            raise NotImplementedError("cannot instantiate %r on your system" 
                                      % (cls.__name__,)) 
        self._init() 
        return self 

你将拥有一个已经理解 int 的 Path 并且可以用来做:

from py._path.local import LocalPath 
 
# extend the types to be converted to string on the fly 
PurePath.types_to_stringify.extend([LocalPath, bool]) 
 
tmpdir = LocalPath('/var/tmp/abc') 
 
p = Path(tmpdir) / 14 / False / 'testfile.yaml' 
print(p) 

得到:

/var/tmp/abc/14/False/testfile.yaml 

(您需要为 <3.4 版本安装软件包 pathlib2 才能在这些版本上运行)。

上面的Path在Python 3.6中可以作为open(p)使用。

适配 _parse_args 可以自动支持 / (__truediv__) 以及 joinpath() 等方法, relative_to() 等