Skip to content

Commit 9a7d3d8

Browse files
committed
Make isdir/isfile/exists faster on Windows
1 parent 498598e commit 9a7d3d8

File tree

5 files changed

+412
-5
lines changed

5 files changed

+412
-5
lines changed

Lib/ntpath.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -852,11 +852,12 @@ def commonpath(paths):
852852

853853

854854
try:
855-
# The genericpath.isdir implementation uses os.stat and checks the mode
856-
# attribute to tell whether or not the path is a directory.
857-
# This is overkill on Windows - just pass the path to GetFileAttributes
855+
# The genericpath's isdir and isfile implementations uses os.stat internally.
856+
# This is overkill on Windows - just pass the path to GetFileAttributesW
858857
# and check the attribute from there.
859858
from nt import _isdir as isdir
859+
from nt import _isfile as isfile
860+
from nt import _exists as exists
860861
except ImportError:
861-
# Use genericpath.isdir as imported above.
862+
# Use genericpath.* as imported above
862863
pass

Lib/test/test_ntpath.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import inspect
12
import ntpath
23
import os
34
import sys
@@ -889,6 +890,18 @@ def test_isjunction(self):
889890
self.assertFalse(ntpath.isjunction('tmpdir'))
890891
self.assertPathEqual(ntpath.realpath('testjunc'), ntpath.realpath('tmpdir'))
891892

893+
@unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32")
894+
def test_fast_paths_in_use(self):
895+
# There are fast paths of these functions implemented in posixmodule.c.
896+
# Confirm that they are being used, and not the Python fallbacks in
897+
# genericpath.py.
898+
self.assertTrue(os.path.isdir is nt._isdir)
899+
self.assertFalse(inspect.isfunction(os.path.isdir))
900+
self.assertTrue(os.path.isfile is nt._isfile)
901+
self.assertFalse(inspect.isfunction(os.path.isfile))
902+
self.assertTrue(os.path.exists is nt._exists)
903+
self.assertFalse(inspect.isfunction(os.path.exists))
904+
892905

893906
class NtCommonTest(test_genericpath.CommonTest, unittest.TestCase):
894907
pathmodule = ntpath
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The functions `os.path.isdir`, `os.path.isfile` and `os.path.exists` are now
2+
13% to 28% faster on Windows, by making fewer win32 API calls.

Modules/clinic/posixmodule.c.h

Lines changed: 200 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)