Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
bpo-42998: add 'username' parameter to pathlib.Path.home()
Slightly re-arrange the internals such that `expanduser()` calls `home()`.
This is to aid with the creation of an `AbstractPath` class in bpo-24132,
where `cwd()` and `home()` will be abstract methods, but not `absolute()`
or `expanduser()`.
  • Loading branch information
barneygale committed Apr 24, 2021
commit 1244a6cf032a7049fdce502a26e882b7a25262ed
12 changes: 9 additions & 3 deletions Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -702,19 +702,25 @@ call fails (for example because the path doesn't exist).
PosixPath('/home/antoine/pathlib')


.. classmethod:: Path.home()
.. classmethod:: Path.home(user=None)

Return a new path object representing the user's home directory (as
Return a new path object representing a user's home directory (as
returned by :func:`os.path.expanduser` with ``~`` construct). If the home
directory can't be resolved, :exc:`RuntimeError` is raised.
directory can't be resolved, :exc:`RuntimeError` is raised. If no user name
is given, the current user's home directory is used.

::

>>> Path.home()
PosixPath('/home/antoine')
>>> Path.home('barney')
PosixPath('/home/barney')

.. versionadded:: 3.5

.. versionchanged:: 3.10
The *user* parameter was added.


.. method:: Path.stat(*, follow_symlinks=True)

Expand Down
18 changes: 12 additions & 6 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1055,14 +1055,22 @@ def cwd(cls):
"""Return a new path pointing to the current working directory
(as returned by os.getcwd()).
"""
return cls(cls()._accessor.getcwd())
return cls(cls._accessor.getcwd())

@classmethod
def home(cls):
def home(cls, user=None):
"""Return a new path pointing to the user's home directory (as
returned by os.path.expanduser('~')).
"""
return cls("~").expanduser()
tilde = "~"
if user is None:
user = ""
elif isinstance(user, bytes):
tilde = b"~"
homedir = cls._accessor.expanduser(tilde + user)
if homedir[:1] == tilde:
raise RuntimeError("Could not determine home directory.")
return cls(homedir)

def samefile(self, other_path):
"""Return whether other_path is the same or not as this file
Expand Down Expand Up @@ -1488,9 +1496,7 @@ def expanduser(self):
"""
if (not (self._drv or self._root) and
self._parts and self._parts[0][:1] == '~'):
homedir = self._accessor.expanduser(self._parts[0])
if homedir[:1] == "~":
raise RuntimeError("Could not determine home directory.")
homedir = self.home(self.parts[0][1:])
return self._from_parts([homedir] + self._parts[1:])

return self
Expand Down