Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply assorted Pyugrade suggestions #4056

Merged
merged 5 commits into from
Nov 20, 2023
Merged
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
15 changes: 6 additions & 9 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1874,7 +1874,7 @@ def _extract_resource(self, manager, zip_path): # noqa: C901
timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])

if not WRITE_SUPPORT:
raise IOError(
raise OSError(
'"os.rename" and "os.unlink" are not supported ' 'on this platform'
)
try:
Expand Down Expand Up @@ -2001,7 +2001,7 @@ def get_metadata(self, name):
if name != 'PKG-INFO':
raise KeyError("No metadata except PKG-INFO is available")

with io.open(self.path, encoding='utf-8', errors="replace") as f:
with open(self.path, encoding='utf-8', errors="replace") as f:
metadata = f.read()
self._warn_on_replacement(metadata)
return metadata
Expand Down Expand Up @@ -2095,8 +2095,7 @@ def find_eggs_in_zip(importer, path_item, only=False):
if _is_egg_path(subitem):
subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
for dist in dists:
yield dist
yield from dists
elif subitem.lower().endswith(('.dist-info', '.egg-info')):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
Expand Down Expand Up @@ -2131,8 +2130,7 @@ def find_on_path(importer, path_item, only=False):
for entry in sorted(entries):
fullpath = os.path.join(path_item, entry)
factory = dist_factory(path_item, entry, only)
for dist in factory(fullpath):
yield dist
yield from factory(fullpath)


def dist_factory(path_item, entry, only):
Expand Down Expand Up @@ -2850,8 +2848,7 @@ def _get_metadata_path_for_display(self, name):

def _get_metadata(self, name):
if self.has_metadata(name):
for line in self.get_metadata_lines(name):
yield line
yield from self.get_metadata_lines(name)

def _get_version(self):
lines = self._get_metadata(self.PKG_INFO)
Expand Down Expand Up @@ -3243,7 +3240,7 @@ def ensure_directory(path):
def _bypass_ensure_directory(path):
"""Sandbox-bypassing version of ensure_directory()"""
if not WRITE_SUPPORT:
raise IOError('"os.mkdir" not supported on this platform.')
raise OSError('"os.mkdir" not supported on this platform.')
dirname, filename = split(path)
if dirname and filename and not isdir(dirname):
_bypass_ensure_directory(dirname)
Expand Down
3 changes: 1 addition & 2 deletions setuptools/command/build_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import os
import fnmatch
import textwrap
import io
import distutils.errors
import itertools
import stat
Expand Down Expand Up @@ -249,7 +248,7 @@ def check_package(self, package, package_dir):
else:
return init_py

with io.open(init_py, 'rb') as f:
with open(init_py, 'rb') as f:
contents = f.read()
if b'declare_namespace' not in contents:
raise distutils.errors.DistutilsError(
Expand Down
3 changes: 1 addition & 2 deletions setuptools/command/develop.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from distutils.errors import DistutilsOptionError
import os
import glob
import io

from setuptools.command.easy_install import easy_install
from setuptools import _path
Expand Down Expand Up @@ -154,7 +153,7 @@ def install_egg_scripts(self, dist):
for script_name in self.distribution.scripts or []:
script_path = os.path.abspath(convert_path(script_name))
script_name = os.path.basename(script_path)
with io.open(script_path) as strm:
with open(script_path) as strm:
script_text = strm.read()
self.install_script(dist, script_name, script_text, script_path)

Expand Down
10 changes: 5 additions & 5 deletions setuptools/command/easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ def check_site_dir(self): # noqa: C901 # is too complex (12) # FIXME
if not os.path.exists(instdir):
try:
os.makedirs(instdir)
except (OSError, IOError):
except OSError:
self.cant_write_to_target()

# Is it a configured, PYTHONPATH, implicit, or explicit site dir?
Expand All @@ -498,7 +498,7 @@ def check_site_dir(self): # noqa: C901 # is too complex (12) # FIXME
os.unlink(testfile)
open(testfile, 'w').close()
os.unlink(testfile)
except (OSError, IOError):
except OSError:
self.cant_write_to_target()

if not is_site_dir and not self.multi_version:
Expand Down Expand Up @@ -594,7 +594,7 @@ def check_pth_processing(self):
dirname = os.path.dirname(ok_file)
os.makedirs(dirname, exist_ok=True)
f = open(pth_file, 'w')
except (OSError, IOError):
except OSError:
self.cant_write_to_target()
else:
try:
Expand Down Expand Up @@ -1995,9 +1995,9 @@ def is_python(text, filename='<string>'):
def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
with io.open(executable, encoding='latin-1') as fp:
with open(executable, encoding='latin-1') as fp:
magic = fp.read(2)
except (OSError, IOError):
except OSError:
return executable
return magic == '#!'

Expand Down
3 changes: 1 addition & 2 deletions setuptools/command/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import distutils.command.sdist as orig
import os
import sys
import io
import contextlib
from itertools import chain

Expand Down Expand Up @@ -189,7 +188,7 @@ def _manifest_is_not_generated(self):
if not os.path.isfile(self.manifest):
return False

with io.open(self.manifest, 'rb') as fp:
with open(self.manifest, 'rb') as fp:
first_line = fp.readline()
return first_line != '# file GENERATED by distutils, do NOT edit\n'.encode()

Expand Down
3 changes: 1 addition & 2 deletions setuptools/command/upload_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from distutils import log
from distutils.errors import DistutilsOptionError
import os
import socket
import zipfile
import tempfile
import shutil
Expand Down Expand Up @@ -201,7 +200,7 @@ def upload_file(self, filename):
conn.putheader('Authorization', auth)
conn.endheaders()
conn.send(body)
except socket.error as e:
except OSError as e:
self.announce(str(e), log.ERROR)
return

Expand Down
3 changes: 1 addition & 2 deletions setuptools/config/expand.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"""
import ast
import importlib
import io
import os
import pathlib
import sys
Expand Down Expand Up @@ -147,7 +146,7 @@ def _filter_existing_files(filepaths: Iterable[_Path]) -> Iterator[_Path]:


def _read_file(filepath: Union[bytes, _Path]) -> str:
with io.open(filepath, encoding='utf-8') as f:
with open(filepath, encoding='utf-8') as f:
return f.read()


Expand Down
2 changes: 1 addition & 1 deletion setuptools/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def _parse_config_files(self, filenames=None): # noqa: C901
parser = ConfigParser()
parser.optionxform = str
for filename in filenames:
with io.open(filename, encoding='utf-8') as reader:
with open(filename, encoding='utf-8') as reader:
if DEBUG:
self.announce(" reading {filename}".format(**locals()))
parser.read_file(reader)
Expand Down
14 changes: 7 additions & 7 deletions setuptools/msvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,17 +567,17 @@ def lookup(self, key, name):
bkey = None
try:
bkey = openkey(hkey, ms(key), 0, key_read)
except (OSError, IOError):
except OSError:
if not self.pi.current_is_x86():
try:
bkey = openkey(hkey, ms(key, True), 0, key_read)
except (OSError, IOError):
except OSError:
continue
else:
continue
try:
return winreg.QueryValueEx(bkey, name)[0]
except (OSError, IOError):
except OSError:
pass
finally:
if bkey:
Expand Down Expand Up @@ -646,7 +646,7 @@ def find_reg_vs_vers(self):
for hkey, key in itertools.product(self.ri.HKEYS, vckeys):
try:
bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)
except (OSError, IOError):
except OSError:
continue
with bkey:
subkeys, values, _ = winreg.QueryInfoKey(bkey)
Expand Down Expand Up @@ -678,7 +678,7 @@ def find_programdata_vs_vers(self):
try:
hashed_names = listdir(instances_dir)

except (OSError, IOError):
except OSError:
# Directory not exists with all Visual Studio versions
return vs_versions

Expand All @@ -698,7 +698,7 @@ def find_programdata_vs_vers(self):
self._as_float_version(state['installationVersion'])
] = vs_path

except (OSError, IOError, KeyError):
except (OSError, KeyError):
# Skip if "state.json" file is missing or bad format
continue

Expand Down Expand Up @@ -784,7 +784,7 @@ def _guess_vc(self):
vc_ver = listdir(guess_vc)[-1]
self.vc_ver = self._as_float_version(vc_ver)
return join(guess_vc, vc_ver)
except (OSError, IOError, IndexError):
except (OSError, IndexError):
return ''

def _guess_vc_legacy(self):
Expand Down
2 changes: 1 addition & 1 deletion setuptools/package_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
'%s returned a bad status line. The server might be '
'down, %s' % (url, v.line)
) from v
except (http.client.HTTPException, socket.error) as v:
except (http.client.HTTPException, OSError) as v:
if warning:
self.warn(warning, v)
else:
Expand Down
2 changes: 1 addition & 1 deletion setuptools/tests/test_core_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def test_maintainer_author(name, attrs, tmpdir):

dist.metadata.write_pkg_info(fn_s)

with io.open(str(fn.join('PKG-INFO')), 'r', encoding='utf-8') as f:
with open(str(fn.join('PKG-INFO')), 'r', encoding='utf-8') as f:
pkg_info = f.read()

assert _valid_metadata(pkg_info)
Expand Down
9 changes: 4 additions & 5 deletions setuptools/tests/test_install_scripts.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""install_scripts tests
"""

import io
import sys

import pytest
Expand Down Expand Up @@ -43,7 +42,7 @@ def test_sys_executable_escaping_unix(self, tmpdir, monkeypatch):
monkeypatch.setattr('sys.executable', self.unix_exe)
with tmpdir.as_cwd():
self._run_install_scripts(str(tmpdir))
with io.open(str(tmpdir.join('foo')), 'r') as f:
with open(str(tmpdir.join('foo')), 'r') as f:
actual = f.readline()
assert actual == expected

Expand All @@ -57,7 +56,7 @@ def test_sys_executable_escaping_win32(self, tmpdir, monkeypatch):
monkeypatch.setattr('sys.executable', self.win32_exe)
with tmpdir.as_cwd():
self._run_install_scripts(str(tmpdir))
with io.open(str(tmpdir.join('foo-script.py')), 'r') as f:
with open(str(tmpdir.join('foo-script.py')), 'r') as f:
actual = f.readline()
assert actual == expected

Expand All @@ -71,7 +70,7 @@ def test_executable_with_spaces_escaping_unix(self, tmpdir):
expected = '#!%s\n' % self.unix_spaces_exe
with tmpdir.as_cwd():
self._run_install_scripts(str(tmpdir), self.unix_spaces_exe)
with io.open(str(tmpdir.join('foo')), 'r') as f:
with open(str(tmpdir.join('foo')), 'r') as f:
actual = f.readline()
assert actual == expected

Expand All @@ -85,6 +84,6 @@ def test_executable_arg_escaping_win32(self, tmpdir):
expected = '#!"%s"\n' % self.win32_exe
with tmpdir.as_cwd():
self._run_install_scripts(str(tmpdir), '"' + self.win32_exe + '"')
with io.open(str(tmpdir.join('foo-script.py')), 'r') as f:
with open(str(tmpdir.join('foo-script.py')), 'r') as f:
actual = f.readline()
assert actual == expected
2 changes: 1 addition & 1 deletion setuptools/tests/test_sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def decompose(path):


def read_all_bytes(filename):
with io.open(filename, 'rb') as fp:
with open(filename, 'rb') as fp:
return fp.read()


Expand Down
5 changes: 2 additions & 3 deletions setuptools/tests/test_setopt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import io
import configparser

from setuptools.command import setopt
Expand All @@ -8,13 +7,13 @@ class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, encoding='utf-8') as reader:
with open(filename, encoding='utf-8') as reader:
parser.read_file(reader)
return parser

@staticmethod
def write_text(file, content):
with io.open(file, 'wb') as strm:
with open(file, 'wb') as strm:
strm.write(content.encode('utf-8'))

def test_utf8_encoding_retained(self, tmpdir):
Expand Down
4 changes: 2 additions & 2 deletions tools/build_launchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def build_cmake_project_with_msbuild(build_arena, msbuild_parameters):
subprocess.check_call(cmd, cwd=build_arena)


@functools.lru_cache()
@functools.lru_cache
def get_cmake():
"""Find CMake using registry."""
import winreg
Expand All @@ -96,7 +96,7 @@ def get_cmake():
return root / 'bin\\CMake.exe'


@functools.lru_cache()
@functools.lru_cache
def get_msbuild():
"""Use VSWhere to find MSBuild."""
vswhere = pathlib.Path(
Expand Down