Skip to content

Commit 8377cd4

Browse files
asottilegiampaolo
authored andcommitted
Clean up code which checked presence of os.{stat,lstat,chmod} (#11643)
1 parent 9c3f284 commit 8377cd4

18 files changed

+21
-70
lines changed

Lib/dbm/dumb.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,8 +278,7 @@ def close(self):
278278
__del__ = close
279279

280280
def _chmod(self, file):
281-
if hasattr(self._os, 'chmod'):
282-
self._os.chmod(file, self._mode)
281+
self._os.chmod(file, self._mode)
283282

284283
def __enter__(self):
285284
return self

Lib/fileinput.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,7 @@ def _readline(self):
357357
fd = os.open(self._filename, mode, perm)
358358
self._output = os.fdopen(fd, "w")
359359
try:
360-
if hasattr(os, 'chmod'):
361-
os.chmod(self._filename, perm)
360+
os.chmod(self._filename, perm)
362361
except OSError:
363362
pass
364363
self._savestdout = sys.stdout

Lib/shutil.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -290,10 +290,8 @@ def copymode(src, dst, *, follow_symlinks=True):
290290
stat_func, chmod_func = os.lstat, os.lchmod
291291
else:
292292
return
293-
elif hasattr(os, 'chmod'):
294-
stat_func, chmod_func = _stat, os.chmod
295293
else:
296-
return
294+
stat_func, chmod_func = _stat, os.chmod
297295

298296
st = stat_func(src)
299297
chmod_func(dst, stat.S_IMODE(st.st_mode))

Lib/tarfile.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1787,10 +1787,9 @@ def gettarinfo(self, name=None, arcname=None, fileobj=None):
17871787
tarinfo = self.tarinfo()
17881788
tarinfo.tarfile = self # Not needed
17891789

1790-
# Use os.stat or os.lstat, depending on platform
1791-
# and if symlinks shall be resolved.
1790+
# Use os.stat or os.lstat, depending on if symlinks shall be resolved.
17921791
if fileobj is None:
1793-
if hasattr(os, "lstat") and not self.dereference:
1792+
if not self.dereference:
17941793
statres = os.lstat(name)
17951794
else:
17961795
statres = os.stat(name)
@@ -2235,11 +2234,10 @@ def chown(self, tarinfo, targetpath, numeric_owner):
22352234
def chmod(self, tarinfo, targetpath):
22362235
"""Set file permissions of targetpath according to tarinfo.
22372236
"""
2238-
if hasattr(os, 'chmod'):
2239-
try:
2240-
os.chmod(targetpath, tarinfo.mode)
2241-
except OSError:
2242-
raise ExtractError("could not change mode")
2237+
try:
2238+
os.chmod(targetpath, tarinfo.mode)
2239+
except OSError:
2240+
raise ExtractError("could not change mode")
22432241

22442242
def utime(self, tarinfo, targetpath):
22452243
"""Set modification time of targetpath according to tarinfo.

Lib/tempfile.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,20 +70,10 @@
7070

7171
_once_lock = _allocate_lock()
7272

73-
if hasattr(_os, "lstat"):
74-
_stat = _os.lstat
75-
elif hasattr(_os, "stat"):
76-
_stat = _os.stat
77-
else:
78-
# Fallback. All we need is something that raises OSError if the
79-
# file doesn't exist.
80-
def _stat(fn):
81-
fd = _os.open(fn, _os.O_RDONLY)
82-
_os.close(fd)
8373

8474
def _exists(fn):
8575
try:
86-
_stat(fn)
76+
_os.lstat(fn)
8777
except OSError:
8878
return False
8979
else:

Lib/test/libregrtest/runtest.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -249,10 +249,8 @@ def cleanup_test_droppings(testname, verbose):
249249
if verbose:
250250
print("%r left behind %s %r" % (testname, kind, name))
251251
try:
252-
# if we have chmod, fix possible permissions problems
253-
# that might prevent cleanup
254-
if (hasattr(os, 'chmod')):
255-
os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
252+
# fix possible permissions problems that might prevent cleanup
253+
os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
256254
nuker(name)
257255
except Exception as msg:
258256
print(("%r left behind %s %r and it couldn't be "

Lib/test/pickletester.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1568,11 +1568,10 @@ def test_structseq(self):
15681568
s = self.dumps(t, proto)
15691569
u = self.loads(s)
15701570
self.assert_is_copy(t, u)
1571-
if hasattr(os, "stat"):
1572-
t = os.stat(os.curdir)
1573-
s = self.dumps(t, proto)
1574-
u = self.loads(s)
1575-
self.assert_is_copy(t, u)
1571+
t = os.stat(os.curdir)
1572+
s = self.dumps(t, proto)
1573+
u = self.loads(s)
1574+
self.assert_is_copy(t, u)
15761575
if hasattr(os, "statvfs"):
15771576
t = os.statvfs(os.curdir)
15781577
s = self.dumps(t, proto)

Lib/test/test_compileall.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ def timestamp_metadata(self):
5757
compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
5858
return data, compare
5959

60-
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
6160
def recreation_check(self, metadata):
6261
"""Check that compileall recreates bytecode when the new metadata is
6362
used."""

Lib/test/test_dbm_dumb.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def test_dumbdbm_creation(self):
4040
f.close()
4141

4242
@unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()')
43-
@unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()')
4443
def test_dumbdbm_creation_mode(self):
4544
try:
4645
old_umask = os.umask(0o002)
@@ -275,7 +274,6 @@ def test_invalid_flag(self):
275274
"'r', 'w', 'c', or 'n'"):
276275
dumbdbm.open(_fname, flag)
277276

278-
@unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()')
279277
def test_readonly_files(self):
280278
with support.temp_dir() as dir:
281279
fname = os.path.join(dir, 'db')

Lib/test/test_fileinput.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,6 @@ def test_readline_os_fstat_raises_OSError(self):
428428
self.assertTrue(os_fstat_replacement.invoked,
429429
"os.fstat() was not invoked")
430430

431-
@unittest.skipIf(not hasattr(os, "chmod"), "os.chmod does not exist")
432431
def test_readline_os_chmod_raises_OSError(self):
433432
"""Tests invoking FileInput.readline() when os.chmod() raises OSError.
434433
This exception should be silently discarded."""

Lib/test/test_mailbox.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -864,7 +864,6 @@ def test_directory_in_folder (self):
864864
pass
865865

866866
@unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()')
867-
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
868867
def test_file_permissions(self):
869868
# Verify that message files are created without execute permissions
870869
msg = mailbox.MaildirMessage(self._template % 0)
@@ -878,7 +877,6 @@ def test_file_permissions(self):
878877
self.assertFalse(mode & 0o111)
879878

880879
@unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()')
881-
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
882880
def test_folder_file_perms(self):
883881
# From bug #3228, we want to verify that the file created inside a Maildir
884882
# subfolder isn't marked as executable.
@@ -1120,7 +1118,6 @@ class TestMbox(_TestMboxMMDF, unittest.TestCase):
11201118
_factory = lambda self, path, factory=None: mailbox.mbox(path, factory)
11211119

11221120
@unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()')
1123-
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
11241121
def test_file_perms(self):
11251122
# From bug #3228, we want to verify that the mailbox file isn't executable,
11261123
# even if the umask is set to something that would leave executable bits set.

Lib/test/test_mmap.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,6 @@ def test_double_close(self):
317317
mf.close()
318318
f.close()
319319

320-
@unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
321320
def test_entire_file(self):
322321
# test mapping of entire file by passing 0 for map length
323322
f = open(TESTFN, "wb+")
@@ -332,7 +331,6 @@ def test_entire_file(self):
332331
mf.close()
333332
f.close()
334333

335-
@unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
336334
def test_length_0_offset(self):
337335
# Issue #10916: test mapping of remainder of file by passing 0 for
338336
# map length with an offset doesn't cause a segfault.
@@ -345,7 +343,6 @@ def test_length_0_offset(self):
345343
with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf:
346344
self.assertRaises(IndexError, mf.__getitem__, 80000)
347345

348-
@unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
349346
def test_length_0_large_offset(self):
350347
# Issue #10959: test mapping of a file by passing 0 for
351348
# map length with a large offset doesn't cause a segfault.

Lib/test/test_os.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,6 @@ def setUp(self):
238238
self.addCleanup(support.unlink, self.fname)
239239
create_file(self.fname, b"ABC")
240240

241-
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
242241
def check_stat_attributes(self, fname):
243242
result = os.stat(fname)
244243

Lib/test/test_posix.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -606,8 +606,6 @@ def test_fstat(self):
606606
finally:
607607
fp.close()
608608

609-
@unittest.skipUnless(hasattr(posix, 'stat'),
610-
'test needs posix.stat()')
611609
def test_stat(self):
612610
self.assertTrue(posix.stat(support.TESTFN))
613611
self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
@@ -658,7 +656,6 @@ def test_mknod(self):
658656
except OSError as e:
659657
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL, errno.EACCES))
660658

661-
@unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
662659
@unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
663660
def test_makedev(self):
664661
st = posix.stat(support.TESTFN)
@@ -755,8 +752,7 @@ def test_chown(self):
755752

756753
# re-create the file
757754
support.create_empty_file(support.TESTFN)
758-
self._test_all_chown_common(posix.chown, support.TESTFN,
759-
getattr(posix, 'stat', None))
755+
self._test_all_chown_common(posix.chown, support.TESTFN, posix.stat)
760756

761757
@unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
762758
def test_fchown(self):

Lib/test/test_shutil.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,6 @@ def onerror(*args):
262262
self.assertIn(errors[1][2][1].filename, possible_args)
263263

264264

265-
@unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod()')
266265
@unittest.skipIf(sys.platform[:6] == 'cygwin',
267266
"This test can't be run on Cygwin (issue #1071513).")
268267
@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
@@ -337,7 +336,6 @@ def raiser(fn, *args, **kwargs):
337336
finally:
338337
os.lstat = orig_lstat
339338

340-
@unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
341339
@support.skip_unless_symlink
342340
def test_copymode_follow_symlinks(self):
343341
tmp_dir = self.mkdtemp()
@@ -1022,14 +1020,12 @@ def _copy_file(self, method):
10221020
file2 = os.path.join(tmpdir2, fname)
10231021
return (file1, file2)
10241022

1025-
@unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
10261023
def test_copy(self):
10271024
# Ensure that the copied file exists and has the same mode bits.
10281025
file1, file2 = self._copy_file(shutil.copy)
10291026
self.assertTrue(os.path.exists(file2))
10301027
self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
10311028

1032-
@unittest.skipUnless(hasattr(os, 'chmod'), 'requires os.chmod')
10331029
@unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
10341030
def test_copy2(self):
10351031
# Ensure that the copied file exists and has the same mode and

Lib/test/test_tempfile.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import re
99
import warnings
1010
import contextlib
11+
import stat
1112
import weakref
1213
from unittest import mock
1314

@@ -16,12 +17,6 @@
1617
from test.support import script_helper
1718

1819

19-
if hasattr(os, 'stat'):
20-
import stat
21-
has_stat = 1
22-
else:
23-
has_stat = 0
24-
2520
has_textmode = (tempfile._text_openflags != tempfile._bin_openflags)
2621
has_spawnl = hasattr(os, 'spawnl')
2722

@@ -433,7 +428,6 @@ def test_choose_directory(self):
433428
finally:
434429
os.rmdir(dir)
435430

436-
@unittest.skipUnless(has_stat, 'os.stat not available')
437431
def test_file_mode(self):
438432
# _mkstemp_inner creates files with the proper mode
439433

@@ -738,7 +732,6 @@ def test_choose_directory(self):
738732
finally:
739733
os.rmdir(dir)
740734

741-
@unittest.skipUnless(has_stat, 'os.stat not available')
742735
def test_mode(self):
743736
# mkdtemp creates directories with the proper mode
744737

@@ -1221,8 +1214,7 @@ def test_truncate_with_size_parameter(self):
12211214
f.write(b'abcdefg\n')
12221215
f.truncate(20)
12231216
self.assertTrue(f._rolled)
1224-
if has_stat:
1225-
self.assertEqual(os.fstat(f.fileno()).st_size, 20)
1217+
self.assertEqual(os.fstat(f.fileno()).st_size, 20)
12261218

12271219

12281220
if tempfile.NamedTemporaryFile is not tempfile.TemporaryFile:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Clean up code which checked presence of ``os.stat`` / ``os.lstat`` /
2+
``os.chmod`` which are always present. Patch by Anthony Sottile.

setup.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2266,7 +2266,6 @@ def install(self):
22662266
return outfiles
22672267

22682268
def set_file_modes(self, files, defaultMode, sharedLibMode):
2269-
if not self.is_chmod_supported(): return
22702269
if not files: return
22712270

22722271
for filename in files:
@@ -2277,16 +2276,12 @@ def set_file_modes(self, files, defaultMode, sharedLibMode):
22772276
if not self.dry_run: os.chmod(filename, mode)
22782277

22792278
def set_dir_modes(self, dirname, mode):
2280-
if not self.is_chmod_supported(): return
22812279
for dirpath, dirnames, fnames in os.walk(dirname):
22822280
if os.path.islink(dirpath):
22832281
continue
22842282
log.info("changing mode of %s to %o", dirpath, mode)
22852283
if not self.dry_run: os.chmod(dirpath, mode)
22862284

2287-
def is_chmod_supported(self):
2288-
return hasattr(os, 'chmod')
2289-
22902285
class PyBuildScripts(build_scripts):
22912286
def copy_scripts(self):
22922287
outfiles, updated_files = build_scripts.copy_scripts(self)

0 commit comments

Comments
 (0)