Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions Doc/library/fnmatch.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,17 @@ patterns.
:const:`False`; the comparison is case-sensitive and does not apply
:func:`os.path.normcase`.

.. versionchanged:: 3.8
Accepts a :term:`path-like object` as *filename*.

.. function:: filter(names, pattern)

Return the subset of the list of *names* that match *pattern*. It is the same as
``[n for n in names if fnmatch(n, pattern)]``, but implemented more efficiently.

.. versionchanged:: 3.8
Accepts :term:`path-like objects <path-like object>` as items of the iterable
*names*.

.. function:: translate(pattern)

Expand Down
4 changes: 2 additions & 2 deletions Lib/fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def filter(names, pat):
if os.path is posixpath:
# normcase on posix is NOP. Optimize it away from the loop.
for name in names:
if match(name):
if match(os.fspath(name)):
result.append(name)
else:
for name in names:
Expand All @@ -68,7 +68,7 @@ def fnmatchcase(name, pat):
its arguments.
"""
match = _compile_pattern(pat)
return match(name) is not None
return match(os.fspath(name)) is not None


def translate(pat):
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@

from fnmatch import fnmatch, fnmatchcase, translate, filter

class Path:
def __init__(self, path):
self.path = path

def __fspath__(self):
return self.path

class FnmatchTestCase(unittest.TestCase):

def check_match(self, filename, pattern, should_match=True, fn=fnmatch):
Expand Down Expand Up @@ -95,6 +102,11 @@ def test_warnings(self):
check(',', '[a-z+--A-Z]')
check('.', '[a-z--/A-Z]')

def test_fspath(self):
check = self.check_match
check(Path('foo.txt'), '*.txt', fn=fnmatch)
check(Path('foo.txt'), '*.txt', fn=fnmatchcase)


class TranslateTestCase(unittest.TestCase):

Expand Down Expand Up @@ -135,6 +147,12 @@ def test_sep(self):
self.assertEqual(filter(['usr/bin', 'usr', 'usr\\lib'], 'usr\\*'),
['usr/bin', 'usr\\lib'] if normsep else ['usr\\lib'])

def test_fspath(self):
path = Path('foo.txt')

self.assertEqual(filter([path], '*.txt*'), [path])
self.assertEqual(filter([path, 'bar.txt'], '*.txt'), [path, 'bar.txt'])


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Added support for :term:`path-like objects <path-like object>` to
:func:`fnmatch.fnmatchcase` and :func:`fnmatch.filter`. Patch by
Andrés Delfino.