Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
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
3 changes: 3 additions & 0 deletions Doc/library/glob.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ The :mod:`glob` module defines the following functions:
.. versionchanged:: 3.11
Added the *include_hidden* parameter.

.. versionchanged:: next
Added ``~`` expansion to user's home directory.


.. function:: iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, \
include_hidden=False)
Expand Down
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,13 @@ getopt
(Contributed by Serhiy Storchaka in :gh:`126390`.)


glob
----

* Add ``~`` expansion to user's home directory.
(Contributed by Stan Ulbrych in :gh:`132757`.)


graphlib
--------

Expand Down
10 changes: 10 additions & 0 deletions Lib/glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ def iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
"""
sys.audit("glob.glob", pathname, recursive)
sys.audit("glob.glob/2", pathname, recursive, root_dir, dir_fd)

# expand ~
from pathlib import Path
tilde = '~' if isinstance(pathname, str) else b'~'
sep = os.sep if isinstance(pathname, str) else os.sep.encode('ascii')
home = str(Path.home()) if isinstance(pathname, str) else bytes(
Path.home())
if pathname == tilde or pathname.startswith(tilde + sep):
pathname = pathname.replace(tilde, home, 1)

if root_dir is not None:
root_dir = os.fspath(root_dir)
else:
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shutil
import sys
import unittest
import unittest.mock
import warnings

from test.support import is_wasi, Py_DEBUG
Expand Down Expand Up @@ -210,6 +211,21 @@ def test_glob_bytes_directory_with_trailing_slash(self):
[os.fsencode(self.norm('aaa') + os.sep),
os.fsencode(self.norm('aab') + os.sep)])

def test_glob_tilde_expansion(self):
with unittest.mock.patch('pathlib.Path.home', return_value=self.tempdir):
results = glob.glob('~')
self.assertEqual([self.tempdir], results)

results = glob.glob(f'~{os.sep}*')
self.assertIn(self.tempdir + f'{os.sep}a', results)

# test it is not expanded when it is not a path
tilde_file = os.path.join(self.tempdir, '~file')
create_empty_file(tilde_file)
with change_cwd(self.tempdir):
results = glob.glob('~*')
self.assertIn('~file', results)

@skip_unless_symlink
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement ``~`` expansion in :func:`glob.glob`.
Loading