Add with_name() and with_suffix() methods.

This commit is contained in:
Antoine Pitrou 2012-10-10 20:55:44 +02:00
parent f390aca7b6
commit 18abe3c987
1 changed files with 64 additions and 27 deletions

View File

@ -306,33 +306,6 @@ to the logical "current directory"::
PurePosixPath('.') PurePosixPath('.')
Joining
-------
A path can be joined with another using the ``__getitem__`` operator::
>>> p = PurePosixPath('foo')
>>> p['bar']
PurePosixPath('foo/bar')
>>> p[PurePosixPath('bar')]
PurePosixPath('foo/bar')
As with constructing, multiple path components can be specified, either
collapsed or separately::
>>> p['bar/xyzzy']
PurePosixPath('foo/bar/xyzzy')
>>> p['bar', 'xyzzy']
PurePosixPath('foo/bar/xyzzy')
A join() method is also provided, with the same behaviour. It can serve
as a factory function::
>>> path_factory = p.join
>>> path_factory('bar')
PurePosixPath('foo/bar')
Representing Representing
------------ ------------
@ -381,6 +354,70 @@ Seven simple properties are provided on every path (each can be empty)::
['.tar', '.gz'] ['.tar', '.gz']
Deriving new paths
------------------
Joining
^^^^^^^
A path can be joined with another using the ``__getitem__`` operator::
>>> p = PurePosixPath('foo')
>>> p['bar']
PurePosixPath('foo/bar')
>>> p[PurePosixPath('bar')]
PurePosixPath('foo/bar')
As with the constructor, multiple path components can be specified, either
collapsed or separately::
>>> p['bar/xyzzy']
PurePosixPath('foo/bar/xyzzy')
>>> p['bar', 'xyzzy']
PurePosixPath('foo/bar/xyzzy')
A join() method is also provided, with the same behaviour. It can serve
as a factory function::
>>> path_factory = p.join
>>> path_factory('bar')
PurePosixPath('foo/bar')
Changing the path name
^^^^^^^^^^^^^^^^^^^^^^
The ``with_name()`` method returns a new path, with the name changed::
>>> p = PureNTPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureNTPath('c:\\Downloads\\setup.py')
It fails with a ``ValueError`` if the path doesn't have an actual name::
>>> p = PureNTPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 875, in with_name
raise ValueError("%r has an empty name" % (self,))
ValueError: PureNTPath('c:\\') has an empty name
>>> p.name
''
Changing the path suffix
^^^^^^^^^^^^^^^^^^^^^^^^
The ``with_suffix()`` method returns a new path with the suffix changed.
However, if the path has no suffix, the new suffix is added::
>>> p = PureNTPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureNTPath('c:\\Downloads\\pathlib.tar.bz2')
>>> p = PureNTPath('README')
>>> p.with_suffix('.bz2')
PureNTPath('README.bz2')
Sequence-like access Sequence-like access
-------------------- --------------------