pathlib.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. import fnmatch
  2. import functools
  3. import io
  4. import ntpath
  5. import os
  6. import posixpath
  7. import re
  8. import sys
  9. import warnings
  10. from _collections_abc import Sequence
  11. from errno import ENOENT, ENOTDIR, EBADF, ELOOP
  12. from operator import attrgetter
  13. from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
  14. from urllib.parse import quote_from_bytes as urlquote_from_bytes
  15. __all__ = [
  16. "PurePath", "PurePosixPath", "PureWindowsPath",
  17. "Path", "PosixPath", "WindowsPath",
  18. ]
  19. #
  20. # Internals
  21. #
  22. _WINERROR_NOT_READY = 21 # drive exists but is not accessible
  23. _WINERROR_INVALID_NAME = 123 # fix for bpo-35306
  24. _WINERROR_CANT_RESOLVE_FILENAME = 1921 # broken symlink pointing to itself
  25. # EBADF - guard against macOS `stat` throwing EBADF
  26. _IGNORED_ERRNOS = (ENOENT, ENOTDIR, EBADF, ELOOP)
  27. _IGNORED_WINERRORS = (
  28. _WINERROR_NOT_READY,
  29. _WINERROR_INVALID_NAME,
  30. _WINERROR_CANT_RESOLVE_FILENAME)
  31. def _ignore_error(exception):
  32. return (getattr(exception, 'errno', None) in _IGNORED_ERRNOS or
  33. getattr(exception, 'winerror', None) in _IGNORED_WINERRORS)
  34. def _is_wildcard_pattern(pat):
  35. # Whether this pattern needs actual matching using fnmatch, or can
  36. # be looked up directly as a file.
  37. return "*" in pat or "?" in pat or "[" in pat
  38. class _Flavour(object):
  39. """A flavour implements a particular (platform-specific) set of path
  40. semantics."""
  41. def __init__(self):
  42. self.join = self.sep.join
  43. def parse_parts(self, parts):
  44. parsed = []
  45. sep = self.sep
  46. altsep = self.altsep
  47. drv = root = ''
  48. it = reversed(parts)
  49. for part in it:
  50. if not part:
  51. continue
  52. if altsep:
  53. part = part.replace(altsep, sep)
  54. drv, root, rel = self.splitroot(part)
  55. if sep in rel:
  56. for x in reversed(rel.split(sep)):
  57. if x and x != '.':
  58. parsed.append(sys.intern(x))
  59. else:
  60. if rel and rel != '.':
  61. parsed.append(sys.intern(rel))
  62. if drv or root:
  63. if not drv:
  64. # If no drive is present, try to find one in the previous
  65. # parts. This makes the result of parsing e.g.
  66. # ("C:", "/", "a") reasonably intuitive.
  67. for part in it:
  68. if not part:
  69. continue
  70. if altsep:
  71. part = part.replace(altsep, sep)
  72. drv = self.splitroot(part)[0]
  73. if drv:
  74. break
  75. break
  76. if drv or root:
  77. parsed.append(drv + root)
  78. parsed.reverse()
  79. return drv, root, parsed
  80. def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
  81. """
  82. Join the two paths represented by the respective
  83. (drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
  84. """
  85. if root2:
  86. if not drv2 and drv:
  87. return drv, root2, [drv + root2] + parts2[1:]
  88. elif drv2:
  89. if drv2 == drv or self.casefold(drv2) == self.casefold(drv):
  90. # Same drive => second path is relative to the first
  91. return drv, root, parts + parts2[1:]
  92. else:
  93. # Second path is non-anchored (common case)
  94. return drv, root, parts + parts2
  95. return drv2, root2, parts2
  96. class _WindowsFlavour(_Flavour):
  97. # Reference for Windows paths can be found at
  98. # http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
  99. sep = '\\'
  100. altsep = '/'
  101. has_drv = True
  102. pathmod = ntpath
  103. is_supported = (os.name == 'nt')
  104. drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  105. ext_namespace_prefix = '\\\\?\\'
  106. reserved_names = (
  107. {'CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'} |
  108. {'COM%s' % c for c in '123456789\xb9\xb2\xb3'} |
  109. {'LPT%s' % c for c in '123456789\xb9\xb2\xb3'}
  110. )
  111. # Interesting findings about extended paths:
  112. # * '\\?\c:\a' is an extended path, which bypasses normal Windows API
  113. # path processing. Thus relative paths are not resolved and slash is not
  114. # translated to backslash. It has the native NT path limit of 32767
  115. # characters, but a bit less after resolving device symbolic links,
  116. # such as '\??\C:' => '\Device\HarddiskVolume2'.
  117. # * '\\?\c:/a' looks for a device named 'C:/a' because slash is a
  118. # regular name character in the object namespace.
  119. # * '\\?\c:\foo/bar' is invalid because '/' is illegal in NT filesystems.
  120. # The only path separator at the filesystem level is backslash.
  121. # * '//?/c:\a' and '//?/c:/a' are effectively equivalent to '\\.\c:\a' and
  122. # thus limited to MAX_PATH.
  123. # * Prior to Windows 8, ANSI API bytes paths are limited to MAX_PATH,
  124. # even with the '\\?\' prefix.
  125. def splitroot(self, part, sep=sep):
  126. first = part[0:1]
  127. second = part[1:2]
  128. if (second == sep and first == sep):
  129. # XXX extended paths should also disable the collapsing of "."
  130. # components (according to MSDN docs).
  131. prefix, part = self._split_extended_path(part)
  132. first = part[0:1]
  133. second = part[1:2]
  134. else:
  135. prefix = ''
  136. third = part[2:3]
  137. if (second == sep and first == sep and third != sep):
  138. # is a UNC path:
  139. # vvvvvvvvvvvvvvvvvvvvv root
  140. # \\machine\mountpoint\directory\etc\...
  141. # directory ^^^^^^^^^^^^^^
  142. index = part.find(sep, 2)
  143. if index != -1:
  144. index2 = part.find(sep, index + 1)
  145. # a UNC path can't have two slashes in a row
  146. # (after the initial two)
  147. if index2 != index + 1:
  148. if index2 == -1:
  149. index2 = len(part)
  150. if prefix:
  151. return prefix + part[1:index2], sep, part[index2+1:]
  152. else:
  153. return part[:index2], sep, part[index2+1:]
  154. drv = root = ''
  155. if second == ':' and first in self.drive_letters:
  156. drv = part[:2]
  157. part = part[2:]
  158. first = third
  159. if first == sep:
  160. root = first
  161. part = part.lstrip(sep)
  162. return prefix + drv, root, part
  163. def casefold(self, s):
  164. return s.lower()
  165. def casefold_parts(self, parts):
  166. return [p.lower() for p in parts]
  167. def compile_pattern(self, pattern):
  168. return re.compile(fnmatch.translate(pattern), re.IGNORECASE).fullmatch
  169. def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix):
  170. prefix = ''
  171. if s.startswith(ext_prefix):
  172. prefix = s[:4]
  173. s = s[4:]
  174. if s.startswith('UNC\\'):
  175. prefix += s[:3]
  176. s = '\\' + s[3:]
  177. return prefix, s
  178. def is_reserved(self, parts):
  179. # NOTE: the rules for reserved names seem somewhat complicated
  180. # (e.g. r"..\NUL" is reserved but not r"foo\NUL" if "foo" does not
  181. # exist). We err on the side of caution and return True for paths
  182. # which are not considered reserved by Windows.
  183. if not parts:
  184. return False
  185. if parts[0].startswith('\\\\'):
  186. # UNC paths are never reserved
  187. return False
  188. name = parts[-1].partition('.')[0].partition(':')[0].rstrip(' ')
  189. return name.upper() in self.reserved_names
  190. def make_uri(self, path):
  191. # Under Windows, file URIs use the UTF-8 encoding.
  192. drive = path.drive
  193. if len(drive) == 2 and drive[1] == ':':
  194. # It's a path on a local drive => 'file:///c:/a/b'
  195. rest = path.as_posix()[2:].lstrip('/')
  196. return 'file:///%s/%s' % (
  197. drive, urlquote_from_bytes(rest.encode('utf-8')))
  198. else:
  199. # It's a path on a network drive => 'file://host/share/a/b'
  200. return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8'))
  201. class _PosixFlavour(_Flavour):
  202. sep = '/'
  203. altsep = ''
  204. has_drv = False
  205. pathmod = posixpath
  206. is_supported = (os.name != 'nt')
  207. def splitroot(self, part, sep=sep):
  208. if part and part[0] == sep:
  209. stripped_part = part.lstrip(sep)
  210. # According to POSIX path resolution:
  211. # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11
  212. # "A pathname that begins with two successive slashes may be
  213. # interpreted in an implementation-defined manner, although more
  214. # than two leading slashes shall be treated as a single slash".
  215. if len(part) - len(stripped_part) == 2:
  216. return '', sep * 2, stripped_part
  217. else:
  218. return '', sep, stripped_part
  219. else:
  220. return '', '', part
  221. def casefold(self, s):
  222. return s
  223. def casefold_parts(self, parts):
  224. return parts
  225. def compile_pattern(self, pattern):
  226. return re.compile(fnmatch.translate(pattern)).fullmatch
  227. def is_reserved(self, parts):
  228. return False
  229. def make_uri(self, path):
  230. # We represent the path using the local filesystem encoding,
  231. # for portability to other applications.
  232. bpath = bytes(path)
  233. return 'file://' + urlquote_from_bytes(bpath)
  234. _windows_flavour = _WindowsFlavour()
  235. _posix_flavour = _PosixFlavour()
  236. #
  237. # Globbing helpers
  238. #
  239. def _make_selector(pattern_parts, flavour):
  240. pat = pattern_parts[0]
  241. child_parts = pattern_parts[1:]
  242. if not pat:
  243. return _TerminatingSelector()
  244. if pat == '**':
  245. cls = _RecursiveWildcardSelector
  246. elif '**' in pat:
  247. raise ValueError("Invalid pattern: '**' can only be an entire path component")
  248. elif _is_wildcard_pattern(pat):
  249. cls = _WildcardSelector
  250. else:
  251. cls = _PreciseSelector
  252. return cls(pat, child_parts, flavour)
  253. if hasattr(functools, "lru_cache"):
  254. _make_selector = functools.lru_cache()(_make_selector)
  255. class _Selector:
  256. """A selector matches a specific glob pattern part against the children
  257. of a given path."""
  258. def __init__(self, child_parts, flavour):
  259. self.child_parts = child_parts
  260. if child_parts:
  261. self.successor = _make_selector(child_parts, flavour)
  262. self.dironly = True
  263. else:
  264. self.successor = _TerminatingSelector()
  265. self.dironly = False
  266. def select_from(self, parent_path):
  267. """Iterate over all child paths of `parent_path` matched by this
  268. selector. This can contain parent_path itself."""
  269. path_cls = type(parent_path)
  270. is_dir = path_cls.is_dir
  271. exists = path_cls.exists
  272. scandir = path_cls._scandir
  273. if not is_dir(parent_path):
  274. return iter([])
  275. return self._select_from(parent_path, is_dir, exists, scandir)
  276. class _TerminatingSelector:
  277. def _select_from(self, parent_path, is_dir, exists, scandir):
  278. yield parent_path
  279. class _PreciseSelector(_Selector):
  280. def __init__(self, name, child_parts, flavour):
  281. self.name = name
  282. _Selector.__init__(self, child_parts, flavour)
  283. def _select_from(self, parent_path, is_dir, exists, scandir):
  284. try:
  285. path = parent_path._make_child_relpath(self.name)
  286. if (is_dir if self.dironly else exists)(path):
  287. for p in self.successor._select_from(path, is_dir, exists, scandir):
  288. yield p
  289. except PermissionError:
  290. return
  291. class _WildcardSelector(_Selector):
  292. def __init__(self, pat, child_parts, flavour):
  293. self.match = flavour.compile_pattern(pat)
  294. _Selector.__init__(self, child_parts, flavour)
  295. def _select_from(self, parent_path, is_dir, exists, scandir):
  296. try:
  297. with scandir(parent_path) as scandir_it:
  298. entries = list(scandir_it)
  299. for entry in entries:
  300. if self.dironly:
  301. try:
  302. # "entry.is_dir()" can raise PermissionError
  303. # in some cases (see bpo-38894), which is not
  304. # among the errors ignored by _ignore_error()
  305. if not entry.is_dir():
  306. continue
  307. except OSError as e:
  308. if not _ignore_error(e):
  309. raise
  310. continue
  311. name = entry.name
  312. if self.match(name):
  313. path = parent_path._make_child_relpath(name)
  314. for p in self.successor._select_from(path, is_dir, exists, scandir):
  315. yield p
  316. except PermissionError:
  317. return
  318. class _RecursiveWildcardSelector(_Selector):
  319. def __init__(self, pat, child_parts, flavour):
  320. _Selector.__init__(self, child_parts, flavour)
  321. def _iterate_directories(self, parent_path, is_dir, scandir):
  322. yield parent_path
  323. try:
  324. with scandir(parent_path) as scandir_it:
  325. entries = list(scandir_it)
  326. for entry in entries:
  327. entry_is_dir = False
  328. try:
  329. entry_is_dir = entry.is_dir()
  330. except OSError as e:
  331. if not _ignore_error(e):
  332. raise
  333. if entry_is_dir and not entry.is_symlink():
  334. path = parent_path._make_child_relpath(entry.name)
  335. for p in self._iterate_directories(path, is_dir, scandir):
  336. yield p
  337. except PermissionError:
  338. return
  339. def _select_from(self, parent_path, is_dir, exists, scandir):
  340. try:
  341. yielded = set()
  342. try:
  343. successor_select = self.successor._select_from
  344. for starting_point in self._iterate_directories(parent_path, is_dir, scandir):
  345. for p in successor_select(starting_point, is_dir, exists, scandir):
  346. if p not in yielded:
  347. yield p
  348. yielded.add(p)
  349. finally:
  350. yielded.clear()
  351. except PermissionError:
  352. return
  353. #
  354. # Public API
  355. #
  356. class _PathParents(Sequence):
  357. """This object provides sequence-like access to the logical ancestors
  358. of a path. Don't try to construct it yourself."""
  359. __slots__ = ('_pathcls', '_drv', '_root', '_parts')
  360. def __init__(self, path):
  361. # We don't store the instance to avoid reference cycles
  362. self._pathcls = type(path)
  363. self._drv = path._drv
  364. self._root = path._root
  365. self._parts = path._parts
  366. def __len__(self):
  367. if self._drv or self._root:
  368. return len(self._parts) - 1
  369. else:
  370. return len(self._parts)
  371. def __getitem__(self, idx):
  372. if isinstance(idx, slice):
  373. return tuple(self[i] for i in range(*idx.indices(len(self))))
  374. if idx >= len(self) or idx < -len(self):
  375. raise IndexError(idx)
  376. if idx < 0:
  377. idx += len(self)
  378. return self._pathcls._from_parsed_parts(self._drv, self._root,
  379. self._parts[:-idx - 1])
  380. def __repr__(self):
  381. return "<{}.parents>".format(self._pathcls.__name__)
  382. class PurePath(object):
  383. """Base class for manipulating paths without I/O.
  384. PurePath represents a filesystem path and offers operations which
  385. don't imply any actual filesystem I/O. Depending on your system,
  386. instantiating a PurePath will return either a PurePosixPath or a
  387. PureWindowsPath object. You can also instantiate either of these classes
  388. directly, regardless of your system.
  389. """
  390. __slots__ = (
  391. '_drv', '_root', '_parts',
  392. '_str', '_hash', '_pparts', '_cached_cparts',
  393. )
  394. def __new__(cls, *args):
  395. """Construct a PurePath from one or several strings and or existing
  396. PurePath objects. The strings and path objects are combined so as
  397. to yield a canonicalized path, which is incorporated into the
  398. new PurePath object.
  399. """
  400. if cls is PurePath:
  401. cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
  402. return cls._from_parts(args)
  403. def __reduce__(self):
  404. # Using the parts tuple helps share interned path parts
  405. # when pickling related paths.
  406. return (self.__class__, tuple(self._parts))
  407. @classmethod
  408. def _parse_args(cls, args):
  409. # This is useful when you don't want to create an instance, just
  410. # canonicalize some constructor arguments.
  411. parts = []
  412. for a in args:
  413. if isinstance(a, PurePath):
  414. parts += a._parts
  415. else:
  416. a = os.fspath(a)
  417. if isinstance(a, str):
  418. # Force-cast str subclasses to str (issue #21127)
  419. parts.append(str(a))
  420. else:
  421. raise TypeError(
  422. "argument should be a str object or an os.PathLike "
  423. "object returning str, not %r"
  424. % type(a))
  425. return cls._flavour.parse_parts(parts)
  426. @classmethod
  427. def _from_parts(cls, args):
  428. # We need to call _parse_args on the instance, so as to get the
  429. # right flavour.
  430. self = object.__new__(cls)
  431. drv, root, parts = self._parse_args(args)
  432. self._drv = drv
  433. self._root = root
  434. self._parts = parts
  435. return self
  436. @classmethod
  437. def _from_parsed_parts(cls, drv, root, parts):
  438. self = object.__new__(cls)
  439. self._drv = drv
  440. self._root = root
  441. self._parts = parts
  442. return self
  443. @classmethod
  444. def _format_parsed_parts(cls, drv, root, parts):
  445. if drv or root:
  446. return drv + root + cls._flavour.join(parts[1:])
  447. else:
  448. return cls._flavour.join(parts)
  449. def _make_child(self, args):
  450. drv, root, parts = self._parse_args(args)
  451. drv, root, parts = self._flavour.join_parsed_parts(
  452. self._drv, self._root, self._parts, drv, root, parts)
  453. return self._from_parsed_parts(drv, root, parts)
  454. def __str__(self):
  455. """Return the string representation of the path, suitable for
  456. passing to system calls."""
  457. try:
  458. return self._str
  459. except AttributeError:
  460. self._str = self._format_parsed_parts(self._drv, self._root,
  461. self._parts) or '.'
  462. return self._str
  463. def __fspath__(self):
  464. return str(self)
  465. def as_posix(self):
  466. """Return the string representation of the path with forward (/)
  467. slashes."""
  468. f = self._flavour
  469. return str(self).replace(f.sep, '/')
  470. def __bytes__(self):
  471. """Return the bytes representation of the path. This is only
  472. recommended to use under Unix."""
  473. return os.fsencode(self)
  474. def __repr__(self):
  475. return "{}({!r})".format(self.__class__.__name__, self.as_posix())
  476. def as_uri(self):
  477. """Return the path as a 'file' URI."""
  478. if not self.is_absolute():
  479. raise ValueError("relative path can't be expressed as a file URI")
  480. return self._flavour.make_uri(self)
  481. @property
  482. def _cparts(self):
  483. # Cached casefolded parts, for hashing and comparison
  484. try:
  485. return self._cached_cparts
  486. except AttributeError:
  487. self._cached_cparts = self._flavour.casefold_parts(self._parts)
  488. return self._cached_cparts
  489. def __eq__(self, other):
  490. if not isinstance(other, PurePath):
  491. return NotImplemented
  492. return self._cparts == other._cparts and self._flavour is other._flavour
  493. def __hash__(self):
  494. try:
  495. return self._hash
  496. except AttributeError:
  497. self._hash = hash(tuple(self._cparts))
  498. return self._hash
  499. def __lt__(self, other):
  500. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  501. return NotImplemented
  502. return self._cparts < other._cparts
  503. def __le__(self, other):
  504. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  505. return NotImplemented
  506. return self._cparts <= other._cparts
  507. def __gt__(self, other):
  508. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  509. return NotImplemented
  510. return self._cparts > other._cparts
  511. def __ge__(self, other):
  512. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  513. return NotImplemented
  514. return self._cparts >= other._cparts
  515. drive = property(attrgetter('_drv'),
  516. doc="""The drive prefix (letter or UNC path), if any.""")
  517. root = property(attrgetter('_root'),
  518. doc="""The root of the path, if any.""")
  519. @property
  520. def anchor(self):
  521. """The concatenation of the drive and root, or ''."""
  522. anchor = self._drv + self._root
  523. return anchor
  524. @property
  525. def name(self):
  526. """The final path component, if any."""
  527. parts = self._parts
  528. if len(parts) == (1 if (self._drv or self._root) else 0):
  529. return ''
  530. return parts[-1]
  531. @property
  532. def suffix(self):
  533. """
  534. The final component's last suffix, if any.
  535. This includes the leading period. For example: '.txt'
  536. """
  537. name = self.name
  538. i = name.rfind('.')
  539. if 0 < i < len(name) - 1:
  540. return name[i:]
  541. else:
  542. return ''
  543. @property
  544. def suffixes(self):
  545. """
  546. A list of the final component's suffixes, if any.
  547. These include the leading periods. For example: ['.tar', '.gz']
  548. """
  549. name = self.name
  550. if name.endswith('.'):
  551. return []
  552. name = name.lstrip('.')
  553. return ['.' + suffix for suffix in name.split('.')[1:]]
  554. @property
  555. def stem(self):
  556. """The final path component, minus its last suffix."""
  557. name = self.name
  558. i = name.rfind('.')
  559. if 0 < i < len(name) - 1:
  560. return name[:i]
  561. else:
  562. return name
  563. def with_name(self, name):
  564. """Return a new path with the file name changed."""
  565. if not self.name:
  566. raise ValueError("%r has an empty name" % (self,))
  567. drv, root, parts = self._flavour.parse_parts((name,))
  568. if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep]
  569. or drv or root or len(parts) != 1):
  570. raise ValueError("Invalid name %r" % (name))
  571. return self._from_parsed_parts(self._drv, self._root,
  572. self._parts[:-1] + [name])
  573. def with_stem(self, stem):
  574. """Return a new path with the stem changed."""
  575. return self.with_name(stem + self.suffix)
  576. def with_suffix(self, suffix):
  577. """Return a new path with the file suffix changed. If the path
  578. has no suffix, add given suffix. If the given suffix is an empty
  579. string, remove the suffix from the path.
  580. """
  581. f = self._flavour
  582. if f.sep in suffix or f.altsep and f.altsep in suffix:
  583. raise ValueError("Invalid suffix %r" % (suffix,))
  584. if suffix and not suffix.startswith('.') or suffix == '.':
  585. raise ValueError("Invalid suffix %r" % (suffix))
  586. name = self.name
  587. if not name:
  588. raise ValueError("%r has an empty name" % (self,))
  589. old_suffix = self.suffix
  590. if not old_suffix:
  591. name = name + suffix
  592. else:
  593. name = name[:-len(old_suffix)] + suffix
  594. return self._from_parsed_parts(self._drv, self._root,
  595. self._parts[:-1] + [name])
  596. def relative_to(self, *other):
  597. """Return the relative path to another path identified by the passed
  598. arguments. If the operation is not possible (because this is not
  599. a subpath of the other path), raise ValueError.
  600. """
  601. # For the purpose of this method, drive and root are considered
  602. # separate parts, i.e.:
  603. # Path('c:/').relative_to('c:') gives Path('/')
  604. # Path('c:/').relative_to('/') raise ValueError
  605. if not other:
  606. raise TypeError("need at least one argument")
  607. parts = self._parts
  608. drv = self._drv
  609. root = self._root
  610. if root:
  611. abs_parts = [drv, root] + parts[1:]
  612. else:
  613. abs_parts = parts
  614. to_drv, to_root, to_parts = self._parse_args(other)
  615. if to_root:
  616. to_abs_parts = [to_drv, to_root] + to_parts[1:]
  617. else:
  618. to_abs_parts = to_parts
  619. n = len(to_abs_parts)
  620. cf = self._flavour.casefold_parts
  621. if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts):
  622. formatted = self._format_parsed_parts(to_drv, to_root, to_parts)
  623. raise ValueError("{!r} is not in the subpath of {!r}"
  624. " OR one path is relative and the other is absolute."
  625. .format(str(self), str(formatted)))
  626. return self._from_parsed_parts('', root if n == 1 else '',
  627. abs_parts[n:])
  628. def is_relative_to(self, *other):
  629. """Return True if the path is relative to another path or False.
  630. """
  631. try:
  632. self.relative_to(*other)
  633. return True
  634. except ValueError:
  635. return False
  636. @property
  637. def parts(self):
  638. """An object providing sequence-like access to the
  639. components in the filesystem path."""
  640. # We cache the tuple to avoid building a new one each time .parts
  641. # is accessed. XXX is this necessary?
  642. try:
  643. return self._pparts
  644. except AttributeError:
  645. self._pparts = tuple(self._parts)
  646. return self._pparts
  647. def joinpath(self, *args):
  648. """Combine this path with one or several arguments, and return a
  649. new path representing either a subpath (if all arguments are relative
  650. paths) or a totally different path (if one of the arguments is
  651. anchored).
  652. """
  653. return self._make_child(args)
  654. def __truediv__(self, key):
  655. try:
  656. return self._make_child((key,))
  657. except TypeError:
  658. return NotImplemented
  659. def __rtruediv__(self, key):
  660. try:
  661. return self._from_parts([key] + self._parts)
  662. except TypeError:
  663. return NotImplemented
  664. @property
  665. def parent(self):
  666. """The logical parent of the path."""
  667. drv = self._drv
  668. root = self._root
  669. parts = self._parts
  670. if len(parts) == 1 and (drv or root):
  671. return self
  672. return self._from_parsed_parts(drv, root, parts[:-1])
  673. @property
  674. def parents(self):
  675. """A sequence of this path's logical parents."""
  676. return _PathParents(self)
  677. def is_absolute(self):
  678. """True if the path is absolute (has both a root and, if applicable,
  679. a drive)."""
  680. if not self._root:
  681. return False
  682. return not self._flavour.has_drv or bool(self._drv)
  683. def is_reserved(self):
  684. """Return True if the path contains one of the special names reserved
  685. by the system, if any."""
  686. return self._flavour.is_reserved(self._parts)
  687. def match(self, path_pattern):
  688. """
  689. Return True if this path matches the given pattern.
  690. """
  691. cf = self._flavour.casefold
  692. path_pattern = cf(path_pattern)
  693. drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
  694. if not pat_parts:
  695. raise ValueError("empty pattern")
  696. if drv and drv != cf(self._drv):
  697. return False
  698. if root and root != cf(self._root):
  699. return False
  700. parts = self._cparts
  701. if drv or root:
  702. if len(pat_parts) != len(parts):
  703. return False
  704. pat_parts = pat_parts[1:]
  705. elif len(pat_parts) > len(parts):
  706. return False
  707. for part, pat in zip(reversed(parts), reversed(pat_parts)):
  708. if not fnmatch.fnmatchcase(part, pat):
  709. return False
  710. return True
  711. # Can't subclass os.PathLike from PurePath and keep the constructor
  712. # optimizations in PurePath._parse_args().
  713. os.PathLike.register(PurePath)
  714. class PurePosixPath(PurePath):
  715. """PurePath subclass for non-Windows systems.
  716. On a POSIX system, instantiating a PurePath should return this object.
  717. However, you can also instantiate it directly on any system.
  718. """
  719. _flavour = _posix_flavour
  720. __slots__ = ()
  721. class PureWindowsPath(PurePath):
  722. """PurePath subclass for Windows systems.
  723. On a Windows system, instantiating a PurePath should return this object.
  724. However, you can also instantiate it directly on any system.
  725. """
  726. _flavour = _windows_flavour
  727. __slots__ = ()
  728. # Filesystem-accessing classes
  729. class Path(PurePath):
  730. """PurePath subclass that can make system calls.
  731. Path represents a filesystem path but unlike PurePath, also offers
  732. methods to do system calls on path objects. Depending on your system,
  733. instantiating a Path will return either a PosixPath or a WindowsPath
  734. object. You can also instantiate a PosixPath or WindowsPath directly,
  735. but cannot instantiate a WindowsPath on a POSIX system or vice versa.
  736. """
  737. __slots__ = ()
  738. def __new__(cls, *args, **kwargs):
  739. if cls is Path:
  740. cls = WindowsPath if os.name == 'nt' else PosixPath
  741. self = cls._from_parts(args)
  742. if not self._flavour.is_supported:
  743. raise NotImplementedError("cannot instantiate %r on your system"
  744. % (cls.__name__,))
  745. return self
  746. def _make_child_relpath(self, part):
  747. # This is an optimization used for dir walking. `part` must be
  748. # a single part relative to this path.
  749. parts = self._parts + [part]
  750. return self._from_parsed_parts(self._drv, self._root, parts)
  751. def __enter__(self):
  752. # In previous versions of pathlib, __exit__() marked this path as
  753. # closed; subsequent attempts to perform I/O would raise an IOError.
  754. # This functionality was never documented, and had the effect of
  755. # making Path objects mutable, contrary to PEP 428.
  756. # In Python 3.9 __exit__() was made a no-op.
  757. # In Python 3.11 __enter__() began emitting DeprecationWarning.
  758. # In Python 3.13 __enter__() and __exit__() should be removed.
  759. warnings.warn("pathlib.Path.__enter__() is deprecated and scheduled "
  760. "for removal in Python 3.13; Path objects as a context "
  761. "manager is a no-op",
  762. DeprecationWarning, stacklevel=2)
  763. return self
  764. def __exit__(self, t, v, tb):
  765. pass
  766. # Public API
  767. @classmethod
  768. def cwd(cls):
  769. """Return a new path pointing to the current working directory
  770. (as returned by os.getcwd()).
  771. """
  772. return cls(os.getcwd())
  773. @classmethod
  774. def home(cls):
  775. """Return a new path pointing to the user's home directory (as
  776. returned by os.path.expanduser('~')).
  777. """
  778. return cls("~").expanduser()
  779. def samefile(self, other_path):
  780. """Return whether other_path is the same or not as this file
  781. (as returned by os.path.samefile()).
  782. """
  783. st = self.stat()
  784. try:
  785. other_st = other_path.stat()
  786. except AttributeError:
  787. other_st = self.__class__(other_path).stat()
  788. return os.path.samestat(st, other_st)
  789. def iterdir(self):
  790. """Iterate over the files in this directory. Does not yield any
  791. result for the special paths '.' and '..'.
  792. """
  793. for name in os.listdir(self):
  794. yield self._make_child_relpath(name)
  795. def _scandir(self):
  796. # bpo-24132: a future version of pathlib will support subclassing of
  797. # pathlib.Path to customize how the filesystem is accessed. This
  798. # includes scandir(), which is used to implement glob().
  799. return os.scandir(self)
  800. def glob(self, pattern):
  801. """Iterate over this subtree and yield all existing files (of any
  802. kind, including directories) matching the given relative pattern.
  803. """
  804. sys.audit("pathlib.Path.glob", self, pattern)
  805. if not pattern:
  806. raise ValueError("Unacceptable pattern: {!r}".format(pattern))
  807. drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
  808. if drv or root:
  809. raise NotImplementedError("Non-relative patterns are unsupported")
  810. if pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  811. pattern_parts.append('')
  812. selector = _make_selector(tuple(pattern_parts), self._flavour)
  813. for p in selector.select_from(self):
  814. yield p
  815. def rglob(self, pattern):
  816. """Recursively yield all existing files (of any kind, including
  817. directories) matching the given relative pattern, anywhere in
  818. this subtree.
  819. """
  820. sys.audit("pathlib.Path.rglob", self, pattern)
  821. drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
  822. if drv or root:
  823. raise NotImplementedError("Non-relative patterns are unsupported")
  824. if pattern and pattern[-1] in (self._flavour.sep, self._flavour.altsep):
  825. pattern_parts.append('')
  826. selector = _make_selector(("**",) + tuple(pattern_parts), self._flavour)
  827. for p in selector.select_from(self):
  828. yield p
  829. def absolute(self):
  830. """Return an absolute version of this path by prepending the current
  831. working directory. No normalization or symlink resolution is performed.
  832. Use resolve() to get the canonical path to a file.
  833. """
  834. if self.is_absolute():
  835. return self
  836. return self._from_parts([self.cwd()] + self._parts)
  837. def resolve(self, strict=False):
  838. """
  839. Make the path absolute, resolving all symlinks on the way and also
  840. normalizing it.
  841. """
  842. def check_eloop(e):
  843. winerror = getattr(e, 'winerror', 0)
  844. if e.errno == ELOOP or winerror == _WINERROR_CANT_RESOLVE_FILENAME:
  845. raise RuntimeError("Symlink loop from %r" % e.filename)
  846. try:
  847. s = os.path.realpath(self, strict=strict)
  848. except OSError as e:
  849. check_eloop(e)
  850. raise
  851. p = self._from_parts((s,))
  852. # In non-strict mode, realpath() doesn't raise on symlink loops.
  853. # Ensure we get an exception by calling stat()
  854. if not strict:
  855. try:
  856. p.stat()
  857. except OSError as e:
  858. check_eloop(e)
  859. return p
  860. def stat(self, *, follow_symlinks=True):
  861. """
  862. Return the result of the stat() system call on this path, like
  863. os.stat() does.
  864. """
  865. return os.stat(self, follow_symlinks=follow_symlinks)
  866. def owner(self):
  867. """
  868. Return the login name of the file owner.
  869. """
  870. try:
  871. import pwd
  872. return pwd.getpwuid(self.stat().st_uid).pw_name
  873. except ImportError:
  874. raise NotImplementedError("Path.owner() is unsupported on this system")
  875. def group(self):
  876. """
  877. Return the group name of the file gid.
  878. """
  879. try:
  880. import grp
  881. return grp.getgrgid(self.stat().st_gid).gr_name
  882. except ImportError:
  883. raise NotImplementedError("Path.group() is unsupported on this system")
  884. def open(self, mode='r', buffering=-1, encoding=None,
  885. errors=None, newline=None):
  886. """
  887. Open the file pointed by this path and return a file object, as
  888. the built-in open() function does.
  889. """
  890. if "b" not in mode:
  891. encoding = io.text_encoding(encoding)
  892. return io.open(self, mode, buffering, encoding, errors, newline)
  893. def read_bytes(self):
  894. """
  895. Open the file in bytes mode, read it, and close the file.
  896. """
  897. with self.open(mode='rb') as f:
  898. return f.read()
  899. def read_text(self, encoding=None, errors=None):
  900. """
  901. Open the file in text mode, read it, and close the file.
  902. """
  903. encoding = io.text_encoding(encoding)
  904. with self.open(mode='r', encoding=encoding, errors=errors) as f:
  905. return f.read()
  906. def write_bytes(self, data):
  907. """
  908. Open the file in bytes mode, write to it, and close the file.
  909. """
  910. # type-check for the buffer interface before truncating the file
  911. view = memoryview(data)
  912. with self.open(mode='wb') as f:
  913. return f.write(view)
  914. def write_text(self, data, encoding=None, errors=None, newline=None):
  915. """
  916. Open the file in text mode, write to it, and close the file.
  917. """
  918. if not isinstance(data, str):
  919. raise TypeError('data must be str, not %s' %
  920. data.__class__.__name__)
  921. encoding = io.text_encoding(encoding)
  922. with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
  923. return f.write(data)
  924. def readlink(self):
  925. """
  926. Return the path to which the symbolic link points.
  927. """
  928. if not hasattr(os, "readlink"):
  929. raise NotImplementedError("os.readlink() not available on this system")
  930. return self._from_parts((os.readlink(self),))
  931. def touch(self, mode=0o666, exist_ok=True):
  932. """
  933. Create this file with the given access mode, if it doesn't exist.
  934. """
  935. if exist_ok:
  936. # First try to bump modification time
  937. # Implementation note: GNU touch uses the UTIME_NOW option of
  938. # the utimensat() / futimens() functions.
  939. try:
  940. os.utime(self, None)
  941. except OSError:
  942. # Avoid exception chaining
  943. pass
  944. else:
  945. return
  946. flags = os.O_CREAT | os.O_WRONLY
  947. if not exist_ok:
  948. flags |= os.O_EXCL
  949. fd = os.open(self, flags, mode)
  950. os.close(fd)
  951. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  952. """
  953. Create a new directory at this given path.
  954. """
  955. try:
  956. os.mkdir(self, mode)
  957. except FileNotFoundError:
  958. if not parents or self.parent == self:
  959. raise
  960. self.parent.mkdir(parents=True, exist_ok=True)
  961. self.mkdir(mode, parents=False, exist_ok=exist_ok)
  962. except OSError:
  963. # Cannot rely on checking for EEXIST, since the operating system
  964. # could give priority to other errors like EACCES or EROFS
  965. if not exist_ok or not self.is_dir():
  966. raise
  967. def chmod(self, mode, *, follow_symlinks=True):
  968. """
  969. Change the permissions of the path, like os.chmod().
  970. """
  971. os.chmod(self, mode, follow_symlinks=follow_symlinks)
  972. def lchmod(self, mode):
  973. """
  974. Like chmod(), except if the path points to a symlink, the symlink's
  975. permissions are changed, rather than its target's.
  976. """
  977. self.chmod(mode, follow_symlinks=False)
  978. def unlink(self, missing_ok=False):
  979. """
  980. Remove this file or link.
  981. If the path is a directory, use rmdir() instead.
  982. """
  983. try:
  984. os.unlink(self)
  985. except FileNotFoundError:
  986. if not missing_ok:
  987. raise
  988. def rmdir(self):
  989. """
  990. Remove this directory. The directory must be empty.
  991. """
  992. os.rmdir(self)
  993. def lstat(self):
  994. """
  995. Like stat(), except if the path points to a symlink, the symlink's
  996. status information is returned, rather than its target's.
  997. """
  998. return self.stat(follow_symlinks=False)
  999. def rename(self, target):
  1000. """
  1001. Rename this path to the target path.
  1002. The target path may be absolute or relative. Relative paths are
  1003. interpreted relative to the current working directory, *not* the
  1004. directory of the Path object.
  1005. Returns the new Path instance pointing to the target path.
  1006. """
  1007. os.rename(self, target)
  1008. return self.__class__(target)
  1009. def replace(self, target):
  1010. """
  1011. Rename this path to the target path, overwriting if that path exists.
  1012. The target path may be absolute or relative. Relative paths are
  1013. interpreted relative to the current working directory, *not* the
  1014. directory of the Path object.
  1015. Returns the new Path instance pointing to the target path.
  1016. """
  1017. os.replace(self, target)
  1018. return self.__class__(target)
  1019. def symlink_to(self, target, target_is_directory=False):
  1020. """
  1021. Make this path a symlink pointing to the target path.
  1022. Note the order of arguments (link, target) is the reverse of os.symlink.
  1023. """
  1024. if not hasattr(os, "symlink"):
  1025. raise NotImplementedError("os.symlink() not available on this system")
  1026. os.symlink(target, self, target_is_directory)
  1027. def hardlink_to(self, target):
  1028. """
  1029. Make this path a hard link pointing to the same file as *target*.
  1030. Note the order of arguments (self, target) is the reverse of os.link's.
  1031. """
  1032. if not hasattr(os, "link"):
  1033. raise NotImplementedError("os.link() not available on this system")
  1034. os.link(target, self)
  1035. def link_to(self, target):
  1036. """
  1037. Make the target path a hard link pointing to this path.
  1038. Note this function does not make this path a hard link to *target*,
  1039. despite the implication of the function and argument names. The order
  1040. of arguments (target, link) is the reverse of Path.symlink_to, but
  1041. matches that of os.link.
  1042. Deprecated since Python 3.10 and scheduled for removal in Python 3.12.
  1043. Use `hardlink_to()` instead.
  1044. """
  1045. warnings.warn("pathlib.Path.link_to() is deprecated and is scheduled "
  1046. "for removal in Python 3.12. "
  1047. "Use pathlib.Path.hardlink_to() instead.",
  1048. DeprecationWarning, stacklevel=2)
  1049. self.__class__(target).hardlink_to(self)
  1050. # Convenience functions for querying the stat results
  1051. def exists(self):
  1052. """
  1053. Whether this path exists.
  1054. """
  1055. try:
  1056. self.stat()
  1057. except OSError as e:
  1058. if not _ignore_error(e):
  1059. raise
  1060. return False
  1061. except ValueError:
  1062. # Non-encodable path
  1063. return False
  1064. return True
  1065. def is_dir(self):
  1066. """
  1067. Whether this path is a directory.
  1068. """
  1069. try:
  1070. return S_ISDIR(self.stat().st_mode)
  1071. except OSError as e:
  1072. if not _ignore_error(e):
  1073. raise
  1074. # Path doesn't exist or is a broken symlink
  1075. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1076. return False
  1077. except ValueError:
  1078. # Non-encodable path
  1079. return False
  1080. def is_file(self):
  1081. """
  1082. Whether this path is a regular file (also True for symlinks pointing
  1083. to regular files).
  1084. """
  1085. try:
  1086. return S_ISREG(self.stat().st_mode)
  1087. except OSError as e:
  1088. if not _ignore_error(e):
  1089. raise
  1090. # Path doesn't exist or is a broken symlink
  1091. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1092. return False
  1093. except ValueError:
  1094. # Non-encodable path
  1095. return False
  1096. def is_mount(self):
  1097. """
  1098. Check if this path is a POSIX mount point
  1099. """
  1100. # Need to exist and be a dir
  1101. if not self.exists() or not self.is_dir():
  1102. return False
  1103. try:
  1104. parent_dev = self.parent.stat().st_dev
  1105. except OSError:
  1106. return False
  1107. dev = self.stat().st_dev
  1108. if dev != parent_dev:
  1109. return True
  1110. ino = self.stat().st_ino
  1111. parent_ino = self.parent.stat().st_ino
  1112. return ino == parent_ino
  1113. def is_symlink(self):
  1114. """
  1115. Whether this path is a symbolic link.
  1116. """
  1117. try:
  1118. return S_ISLNK(self.lstat().st_mode)
  1119. except OSError as e:
  1120. if not _ignore_error(e):
  1121. raise
  1122. # Path doesn't exist
  1123. return False
  1124. except ValueError:
  1125. # Non-encodable path
  1126. return False
  1127. def is_block_device(self):
  1128. """
  1129. Whether this path is a block device.
  1130. """
  1131. try:
  1132. return S_ISBLK(self.stat().st_mode)
  1133. except OSError as e:
  1134. if not _ignore_error(e):
  1135. raise
  1136. # Path doesn't exist or is a broken symlink
  1137. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1138. return False
  1139. except ValueError:
  1140. # Non-encodable path
  1141. return False
  1142. def is_char_device(self):
  1143. """
  1144. Whether this path is a character device.
  1145. """
  1146. try:
  1147. return S_ISCHR(self.stat().st_mode)
  1148. except OSError as e:
  1149. if not _ignore_error(e):
  1150. raise
  1151. # Path doesn't exist or is a broken symlink
  1152. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1153. return False
  1154. except ValueError:
  1155. # Non-encodable path
  1156. return False
  1157. def is_fifo(self):
  1158. """
  1159. Whether this path is a FIFO.
  1160. """
  1161. try:
  1162. return S_ISFIFO(self.stat().st_mode)
  1163. except OSError as e:
  1164. if not _ignore_error(e):
  1165. raise
  1166. # Path doesn't exist or is a broken symlink
  1167. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1168. return False
  1169. except ValueError:
  1170. # Non-encodable path
  1171. return False
  1172. def is_socket(self):
  1173. """
  1174. Whether this path is a socket.
  1175. """
  1176. try:
  1177. return S_ISSOCK(self.stat().st_mode)
  1178. except OSError as e:
  1179. if not _ignore_error(e):
  1180. raise
  1181. # Path doesn't exist or is a broken symlink
  1182. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1183. return False
  1184. except ValueError:
  1185. # Non-encodable path
  1186. return False
  1187. def expanduser(self):
  1188. """ Return a new path with expanded ~ and ~user constructs
  1189. (as returned by os.path.expanduser)
  1190. """
  1191. if (not (self._drv or self._root) and
  1192. self._parts and self._parts[0][:1] == '~'):
  1193. homedir = os.path.expanduser(self._parts[0])
  1194. if homedir[:1] == "~":
  1195. raise RuntimeError("Could not determine home directory.")
  1196. return self._from_parts([homedir] + self._parts[1:])
  1197. return self
  1198. class PosixPath(Path, PurePosixPath):
  1199. """Path subclass for non-Windows systems.
  1200. On a POSIX system, instantiating a Path should return this object.
  1201. """
  1202. __slots__ = ()
  1203. class WindowsPath(Path, PureWindowsPath):
  1204. """Path subclass for Windows systems.
  1205. On a Windows system, instantiating a Path should return this object.
  1206. """
  1207. __slots__ = ()
  1208. def is_mount(self):
  1209. raise NotImplementedError("Path.is_mount() is unsupported on this system")