Core Path API
pathlib_next.path
Object-oriented filesystem paths.
This module provides classes to represent abstract paths and concrete paths with operations that have semantics appropriate for different operating systems.
FsPathLike
Bases: Protocol
Anything implementing __fspath__ -- registered with os.PathLike
so os.fspath() and friends accept it.
Path
Bases: Pathname, Chmod, Stat, BinaryOpen
Base class for manipulating paths with I/O.
__init_subclass__(**kwargs)
Guarantee pathlib_next operation precedence in every subclass.
Concrete path classes are routinely built by mixing a pathlib
class with this one -- our own LocalPath does it, and the
documented downstream recipe (class X(PosixPathname, Path)) does
it transitively. Python's MRO then resolves a name to whichever
base declares it first, which for those classes can be pathlib
rather than pathlib_next -- and which one wins changes with the
interpreter version, because stdlib pathlib keeps gaining and
changing methods (see _OPERATION_NAMES).
Rather than making every downstream implementer rediscover this and hand-write forwarding methods, re-assert our implementations here for any subclass that would otherwise inherit a non-pathlib_next one. A subclass (or an intermediate mixin) that defines the method itself is always left alone -- this only displaces implementations coming from outside this library.
Source code in src/pathlib_next/path.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | |
copy(target, *, overwrite=False, follow_symlinks=True, preserve_metadata=True, recursive=False, ignore_error=None, progress=None)
Copy this file's content to target.
follow_symlinks/preserve_metadata are named to match CPython
3.14's Path.copy() (added after this method); overwrite is our
own extension (3.14 has no equivalent -- it always raises if the
destination exists). preserve_metadata defaults to True here
(unlike 3.14's False) to match this method's pre-existing behavior
of always propagating st_mode; only st_mode is preserved, not
timestamps/xattrs -- full metadata preservation is not implemented.
ignore_error accepts a bool or a callable, matching Path.rm()'s
bool-or-callable contract. True ignores every error; False and
None (the default) fail on the first error. A callable is invoked
as ignore_error(error) -- this call site's own arity -- and, as it
always has here, is a notification hook: the error is suppressed
regardless of what it returns, so handlers like errors.append
(returning None) keep working. Only errors from child copies
during a recursive=True copy are routed here.
progress, when given, is called as progress(path, bytes_copied,
total_size) for every chunk written during each file copy (path
is the source Path being streamed -- self for a single-file
copy, or the relevant child during a recursive=True copy).
bytes_copied increases monotonically per file and reaches
total_size (or None if the size couldn't be determined) at the
end of that file. Directories themselves don't get a progress call
(only the files inside them do). With progress=None (the
default), behavior is unchanged -- no per-chunk overhead. Native
backend transfers that bypass the generic streaming copy (e.g.
SftpPath's asyncssh concurrent fan-out) do not invoke progress;
see docs/divergences.md's "Deliberate extensions" section.
Source code in src/pathlib_next/path.py
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 | |
glob(pattern, *, case_sensitive=None, include_hidden=True, recursive=None, dironly=None, recurse_symlinks=False, native=True, on_error=None, bound_loops=False)
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
Pathlib semantics: hidden entries are matched (include_hidden=False
filters them out and skips hidden directories), a trailing separator
selects directories only, "" never descends into a directory
symlink, and a trailing "" also selects files on Python 3.13+
(directories only before). A missing or non-directory parent selects
nothing. An empty pattern raises ValueError, an absolute one
glob.NonRelativePatternError (a NotImplementedError and a
ValueError). recurse_symlinks=True is not supported.
pattern=None expands the pattern THIS PATH CARRIES
(LocalPath("/etc/*.conf").glob(None)) instead of applying one to a
directory: the path is split at its first wildcard and globbed from
there. "" still raises, as pathlib does. Every keyword means what
it does for a pattern argument -- recursive=None auto-enables
recursion for a carried "**", and native= applies. include_hidden
keeps THIS method's default (True); the module-level
utils.glob.glob() this delegates to defaults it to False,
stdlib-glob-style, so the two spellings differ on hidden names
unless the keyword is passed.
native=True (the default) follows the running interpreter on the
two rules pathlib changed mid-series: a trailing "/" is ignored
before 3.11, and a component that merely contains "" ("a")
raises ValueError before 3.13. native=False applies one rule on
every version -- trailing "/" always selects directories only, "a**"
is always a plain wildcard -- so a pattern answers the same
everywhere, which is what a cross-backend or cross-version caller
usually wants.
on_error(error) is called when a directory cannot be listed, the
same contract as walk() and os.walk: raising from it propagates
(an unreadable directory becomes an error), returning treats that
directory as empty. Without it such a listing is skipped silently --
pathlib's behaviour, and the reason a config loader could not tell a
missing layer from an unreadable one. error.filename names the
directory even when the backend left it empty.
bound_loops=True descends a directory at most once per "**",
keyed on (st_dev, st_ino): that bounds a Windows junction loop,
which no symlink check can see (a junction reports
is_symlink() == False, so recurse_symlinks=False does not help
and pathlib itself loops until the recursion limit). A backend whose
stat carries no identity is walked unbounded, as before.
A "" component auto-enables recursion. Pass recursive=False
explicitly to treat "" as a plain "*" instead.
Note for remote schemes (http/sftp): a recursive glob walks the
whole remote subtree, one request/roundtrip per directory.
Source code in src/pathlib_next/path.py
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
is_dir_binding()
Whether this directory is another tree's second NAME rather than part of this one: a Windows junction or a mount point (bind or otherwise).
The distinction that matters to anything walking a tree. A symlink
announces itself -- is_symlink() is True and every walker here
already declines to follow one. A binding does not: it looks like an
ordinary directory, and its contents belong to whoever mounted or
junctioned it. rm(recursive=True) removes the binding itself
rather than the contents behind it.
An implementation that cannot answer (stdlib's is_mount() raises
on Windows before 3.12) counts as "not a binding" rather than
breaking the operation that asked.
Source code in src/pathlib_next/path.py
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | |
is_hidden()
Return True if the final path component is a hidden file/directory.
Source code in src/pathlib_next/path.py
662 663 664 | |
is_junction()
Whether this path is a Windows junction (pathlib 3.12 parity).
A junction is NOT a symlink: it is a second NAME for a directory,
the Windows equivalent of a Linux bind mount. is_symlink() is
False for one, readlink() does not describe it, and a
non-following stat reports a plain directory -- which is exactly why
a symlink check cannot protect a recursive walk from it.
Default False; LocalPath/FileUri answer for real. A remote
scheme has no such concept unless it says otherwise.
Source code in src/pathlib_next/path.py
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 | |
is_mount()
Whether this path is a mount point (pathlib parity).
The POSIX half of the same idea: a bind mount makes one tree visible
under a second name, with no link anywhere to say so. Default False;
LocalPath/FileUri answer for real.
Source code in src/pathlib_next/path.py
1200 1201 1202 1203 1204 1205 1206 1207 | |
iterdir()
Yield path objects of the directory contents.
The children are yielded in arbitrary order, and the special entries '.' and '..' are not included.
Source code in src/pathlib_next/path.py
694 695 696 697 698 699 700 701 | |
mkdir(mode=511, parents=False, exist_ok=False)
Create a new directory at this given path.
Source code in src/pathlib_next/path.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 | |
move(target, *, overwrite=False)
Move this file or directory to target, falling back to copy+unlink/rm if rename is unsupported.
Source code in src/pathlib_next/path.py
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 | |
rename(target)
Rename this file or directory to the given target.
Source code in src/pathlib_next/path.py
1238 1239 1240 1241 | |
rglob(pattern, *, case_sensitive=None, include_hidden=True, recursive=True, dironly=None, recurse_symlinks=False, native=True, on_error=None, bound_loops=False)
Equivalent to glob(f"**/{pattern}", recursive=True).
pattern=None and native= mean what they do on glob(); with
None this is glob(None, recursive=True), since a carried pattern
brings its own anchor and nothing can be prefixed to it.
Source code in src/pathlib_next/path.py
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 | |
rm(recursive=False, missing_ok=False, ignore_error=False, *, follow_symlinks=False, follow_binds=False)
Remove this file or directory, optionally recursively and ignoring errors.
follow_symlinks applies to a symlink met during a recursive
removal, follow_binds to a binding -- a directory that is another
tree's second NAME rather than part of this one (is_dir_binding():
a Windows junction, a mount point, a bind mount). Both take:
False(default) -- remove the entry itself, never what is behind it:unlink()for a symlink,rmdir()for a binding. This is whatrm -rdoes, and on a live mount thermdir()fails rather than emptying someone else's filesystem.True-- remove the contents behind it, then the entry. What a walker that cannot tell the difference does by accident.None-- leave it in place. The enclosing directory is then not empty, so its own removal reports that.- a callable
policy(path) -> bool | None-- asked per entry with the same three answers, so one tree can keep one mount and follow another.
Path components BEFORE the final one are followed as usual; these
decide what happens to the entry itself. The name matches
stat()/walk()/copy()'s follow_symlinks= rather than
inventing a second vocabulary for the same idea.
Source code in src/pathlib_next/path.py
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 | |
rmdir()
Remove this directory. The directory must be empty.
Source code in src/pathlib_next/path.py
1009 1010 1011 1012 1013 | |
samefile(other_path)
Return whether other_path is the same or not as this file, by comparing (st_dev, st_ino) when the backend's stat() provides them. Raises NotImplementedError otherwise (e.g. our own FileStat doesn't carry st_dev/st_ino) -- LocalPath gets a real implementation from pathlib.Path via MRO instead of this one.
Source code in src/pathlib_next/path.py
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | |
symlink_to(target, target_is_directory=False, *, force=False)
Make this path a symlink pointing to target.
Signature-compatible with pathlib.Path.symlink_to(); force is a
pathlib_next extension (see docs/divergences.md).
With force=True, an existing entry at this path is removed
first. No filesystem or transport offers an atomic "replace a
symlink" operation, so this is an unlink-then-symlink sequence and
is therefore not atomic: between the two steps the path does not
exist, and a concurrent writer can win the race. It is a
convenience, not a locking primitive.
Only a non-directory entry is removed -- an existing directory at
the link path is left alone and the underlying FileExistsError
(or the backend's equivalent) propagates. Silently deleting a
directory tree is never what force= on a symlink call is asking
for.
Source code in src/pathlib_next/path.py
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 | |
touch(mode=None, exist_ok=True)
Create this file, if it doesn't exist.
Raises FileExistsError if exist_ok is False and the file already exists (pathlib parity). An existing file is never truncated.
Differences from pathlib.Path.touch, which creates through
os.open() (so the process umask applies) and bumps an existing
file's mtime:
modeis applied withchmod()only when passed explicitly, and then verbatim: a remote server's umask is unknowable. The default (None) leaves a new file with the permissions the backend gives it, instead of chmod'ing it to a world-writable 0o666.- An existing file's mtime is left unchanged: the generic protocol
has no timestamp primitive, and rewriting the content to bump it
is not a touch.
LocalPathandFileUriuse pathlib's own touch.
Source code in src/pathlib_next/path.py
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 | |
unlink(missing_ok=False)
Remove this file or link. If the path is a directory, use rmdir() instead.
Source code in src/pathlib_next/path.py
1002 1003 1004 1005 1006 1007 | |
walk(top_down=True, on_error=None, follow_symlinks=False)
Walk the directory tree from this directory, similar to os.walk().
Uses _scandir() rather than iterdir() + a stat() per entry --
for schemes whose listing already carries type metadata (HTTP/DAV
indexes, SFTP listdir_attr, FTP MLSD, S3 list pages), this turns a
remote-tree walk from O(entries) round trips into O(dirs). The
pre-seeded stat is trusted only when follow_symlinks is False
(matching walk()'s own default and the lstat-like semantics of
those listing calls); an explicit follow_symlinks=True always
re-stat()s each entry so a symlink is still resolved.
Source code in src/pathlib_next/path.py
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
Pathname
Bases: FsPathLike, Generic[_P]
Base class for manipulating paths without I/O.
anchor
property
drive + root.
drive
property
No generic concept of a drive; always "". LocalPath gets a real one from pathlib on Windows.
name
property
The final path component, if any.
parent
abstractmethod
property
The logical parent of the path.
parents
property
An immutable sequence providing access to the logical ancestors of the path.
parts
abstractmethod
property
The individual components/parts of the path.
root
property
The root of the path, if any (e.g. "/"). See docs/divergences.md
for how this is derived generically vs. LocalPath's real one.
segments
abstractmethod
property
The sequence of path component strings.
stem
property
The final path component, minus its last suffix.
suffix
property
The final component's last suffix, if any.
This includes the leading period. For example: '.txt'
suffixes
property
A list of the final component's suffixes, if any.
These include the leading periods. For example: ['.tar', '.gz']
__eq__(other)
Compare by (exact type, segments).
The ABC previously defined no equality at all, so every pure
subclass that didn't hand-write one -- including MemPath, the
documented reference exemplar -- compared by identity. That made
is_relative_to() (which decides via ==) silently return False
for every subclass, and broke paths as dict keys or set members.
_BaseFSPathname/LocalPath are unaffected: pathlib.PurePath
precedes Pathname in their MRO and keeps its own __eq__, as
does Uri, which defines one.
Source code in src/pathlib_next/path.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
__rtruediv__(key)
"prefix" / path, as pathlib supports. self is passed as an
object, so per-instance state it carries (a MemPath backend)
survives, and an absolute self restarts the join.
Source code in src/pathlib_next/path.py
281 282 283 284 285 286 287 288 289 290 | |
as_posix()
Return the string representation of the path with forward slashes.
Source code in src/pathlib_next/path.py
411 412 413 | |
as_uri()
abstractmethod
Return the path as a URI string.
Source code in src/pathlib_next/path.py
144 145 146 147 | |
full_match(pattern, *, case_sensitive=None)
Return True if this path matches the glob-style pattern
against the whole path (3.13 parity). Unlike match(), this isn't a
right-anchored partial match, and "**" matches any number of path
segments (including zero).
Source code in src/pathlib_next/path.py
401 402 403 404 405 406 407 408 409 | |
has_glob_pattern()
Return True if any of the path segments contain glob wildcards.
The anchor is not one of them: a Windows extended-length path
(\\?\C:\data, and the \\?\UNC\server\share form) carries a
literal ? in its drive, which is a prefix, not a wildcard -- so a
caller asking "is this a pattern or a plain path?" got True for
every such path.
Source code in src/pathlib_next/path.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
is_absolute()
True if the path is absolute
Source code in src/pathlib_next/path.py
324 325 326 327 | |
is_relative_to(other)
Return True if the path is relative to another path or False.
Source code in src/pathlib_next/path.py
243 244 245 246 247 248 249 250 251 252 253 254 | |
joinpath(*args)
Combine this path with one or more paths/segments.
Source code in src/pathlib_next/path.py
292 293 294 | |
match(path_pattern, *, case_sensitive=None)
Return True if this path matches the given glob-style pattern.
pathlib's semantics on the running interpreter: a relative pattern
matches the last N segments (from the right), an absolute pattern
must match the whole path, and each segment is matched on its own,
so * never crosses a "/". "*" acts like "" (use full_match()
for recursive matching). An empty pattern raises ValueError.
A compiled re.Pattern cannot be split into segments; it is matched
against the whole path string instead ("/"-joined segments, so a
Uri's scheme and host are never part of it).
Source code in src/pathlib_next/path.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
relative_to(other)
abstractmethod
Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.
Source code in src/pathlib_next/path.py
235 236 237 238 239 240 241 | |
with_name(name)
Return a new path with the name changed.
Raises ValueError for an empty name, ".", or a name containing "/",
as pathlib does. Without the check a name such as "../../etc/passwd"
or "x/y" was spliced in verbatim, so a caller relying on pathlib's
validation of an untrusted file name got a path outside the
directory. A bare ".." is accepted, also as pathlib does; use
utils.is_safe_child_name() to reject it. with_stem()/
with_suffix() validate their result through here.
Source code in src/pathlib_next/path.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
with_segments(*segments)
abstractmethod
Construct a same-type path instance from new segments.
Source code in src/pathlib_next/path.py
190 191 192 193 | |
with_stem(stem)
Return a new path with the stem changed (validated like
with_name()).
Source code in src/pathlib_next/path.py
212 213 214 215 | |
with_suffix(suffix)
Return a new path with the suffix changed or added.
Source code in src/pathlib_next/path.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
pathlib_next.fspath
LocalPath
Bases: WindowsPath if name == 'nt' else PosixPath, Path, _BaseFSPathname
The real local filesystem path: pathlib.WindowsPath/PosixPath
with this library's Path mixed in via MRO. Behaves exactly like
pathlib.Path for anything not explicitly overridden here (see
docs/divergences.md).
glob(pattern, *, case_sensitive=None, include_hidden=True, recursive=None, dironly=None, recurse_symlinks=False, native=True, on_error=None, bound_loops=False)
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.
Same semantics as Path.glob(), including pattern=None (expand the
pattern this path carries) and native= (follow the running
interpreter, or one rule on every version); every separator of this
flavour splits the pattern, and a pattern with a drive or root
raises glob.NonRelativePatternError like pathlib.
Source code in src/pathlib_next/fspath.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | |
is_junction()
Whether this is a Windows junction. os.path.isjunction() on
3.12+, the reparse tag directly before that.
lstat() reports a junction (IO_REPARSE_TAG_MOUNT_POINT) as a plain
directory -- CPython only rewrites the mode to S_IFLNK for real
symlinks -- so rm(recursive=True) used to walk into one and delete
the target's files. shutil.rmtree guards the same case.
Source code in src/pathlib_next/fspath.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | |
is_mount()
Whether this is a mount point -- a bind mount included, which is how POSIX spells what a junction does on Windows.
Source code in src/pathlib_next/fspath.py
269 270 271 272 273 274 275 | |
PosixPathname
Bases: PurePosixPath, _BaseFSPathname
Pure (no I/O) POSIX-flavour path, implementing the Pathname
protocol on top of pathlib.PurePosixPath.
WindowsPathname
Bases: PureWindowsPath, _BaseFSPathname
Pure (no I/O) Windows-flavour path, implementing the Pathname
protocol on top of pathlib.PureWindowsPath.