Python pathlib.path允许除字符串和路径之外的其他类型连接
如何更改Python pathlib.path允许除字符串和路径之外的其他类型连接,python,python-3.x,pathlib,Python,Python 3.x,Pathlib,如何更改pathlib.Path.\u parse_args,以便我不仅可以将其他类型(如LocalPath)作为Path的参数,还可以将其他类型用作基于/的联接的参数,等等 from pathlib import Path Path(tmplib) / 25 / True 使用tmplibaLocalPathfrompy.\u path.local,其他的自动转换为它们的str()表示 我尝试了次分类和猴子补丁,如这个()问题所示,但没有成功 Path看起来很难扩展。pathlib(和pat
pathlib.Path.\u parse_args
,以便我不仅可以将其他类型(如LocalPath
)作为Path
的参数,还可以将其他类型用作基于/
的联接的参数,等等
from pathlib import Path
Path(tmplib) / 25 / True
使用tmplib
aLocalPath
frompy.\u path.local
,其他的自动转换为它们的str()
表示
我尝试了次分类和猴子补丁,如这个()问题所示,但没有成功
Path
看起来很难扩展。pathlib
(和pathlib2
(适用于Python版本<3.4)主要由四个直接与路径相关的类组成Path
,PosixPath
,WindowsPath
和PurePath
(pathlib2
中的BasePath
)。如果您对其中每一个进行子类化,并复制和调整Path.\uuuu new\uuuuu()
和PurePath.\u parse\u 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
要获得:
/var/tmp/abc/14/False/testfile.yaml
(对于<3.4版本,您需要安装packagepathlib2
,才能在这些版本上工作)
上面的路径
可以在Python 3.6中用作open(p)
调整
\u parse\u args
可以自动支持//code>(\u truediv\u
)以及joinpath()
、relative\u to()
等方法。如果您想保持平台独立性,可以这样做:
from py._path.local import LocalPath
import os
import pathlib
class Path(pathlib.Path):
def __new__(cls, *args, **kwargs):
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
return cls._from_parts(map(str, args))
def __truediv__(self, other):
return super().__truediv__(str(other))
class WindowsPath(Path, pathlib.WindowsPath):
pass
class PosixPath(Path, pathlib.PosixPath):
pass
p = Path(LocalPath())
print(p / 25 / True)
或者,如果可以针对特定平台:
from py._path.local import LocalPath
import pathlib
class Path(pathlib.PosixPath):
def __new__(cls, *args, **kwargs):
return cls._from_parts(map(str, args))
def __truediv__(self, other):
return super().__truediv__(str(other))
p = Path(LocalPath())
print(p / 25 / True)
虽然它看起来比我的解决方案简单,但这不会抱怨任何可以表示为字符串的类型。如果您想使用joinpath()
,reactive\u to()
等,那么您还必须引入这些定义中的每一个。
from py._path.local import LocalPath
import pathlib
class Path(pathlib.PosixPath):
def __new__(cls, *args, **kwargs):
return cls._from_parts(map(str, args))
def __truediv__(self, other):
return super().__truediv__(str(other))
p = Path(LocalPath())
print(p / 25 / True)