bpo-39899: os.path.expanduser(): don't guess other Windows users' home directories if the basename of the current user's home directory doesn't match their username. (GH-18841)
This makes `ntpath.expanduser()` match `pathlib.Path.expanduser()` in this regard, and is more in line with `posixpath.expanduser()`'s cautious approach.
Also remove the near-duplicate implementation of `expanduser()` in pathlib, and by doing so fix a bug where KeyError could be raised when expanding another user's home directory.
diff --git a/Doc/library/os.path.rst b/Doc/library/os.path.rst
index 251df4d..e2f335e 100644
--- a/Doc/library/os.path.rst
+++ b/Doc/library/os.path.rst
@@ -175,8 +175,8 @@
On Windows, :envvar:`USERPROFILE` will be used if set, otherwise a combination
of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be used. An initial
- ``~user`` is handled by stripping the last directory component from the created
- user path derived above.
+ ``~user`` is handled by checking that the last directory component of the current
+ user's home directory matches :envvar:`USERNAME`, and replacing it if so.
If the expansion fails or if the path does not begin with a tilde, the path is
returned unchanged.
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst
index e269bf9..f15fed3 100644
--- a/Doc/library/pathlib.rst
+++ b/Doc/library/pathlib.rst
@@ -705,7 +705,10 @@
.. classmethod:: Path.home()
Return a new path object representing the user's home directory (as
- returned by :func:`os.path.expanduser` with ``~`` construct)::
+ returned by :func:`os.path.expanduser` with ``~`` construct). If the home
+ directory can't be resolved, :exc:`RuntimeError` is raised.
+
+ ::
>>> Path.home()
PosixPath('/home/antoine')
@@ -773,7 +776,10 @@
.. method:: Path.expanduser()
Return a new path with expanded ``~`` and ``~user`` constructs,
- as returned by :meth:`os.path.expanduser`::
+ as returned by :meth:`os.path.expanduser`. If a home directory can't be
+ resolved, :exc:`RuntimeError` is raised.
+
+ ::
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()