Skip to content

Commit

Permalink
Apply more assorted Pyugrade suggestions (#4125)
Browse files Browse the repository at this point in the history
  • Loading branch information
abravalheri committed Jan 5, 2024
2 parents e50a9f2 + 07774d9 commit d3048fc
Show file tree
Hide file tree
Showing 19 changed files with 86 additions and 81 deletions.
8 changes: 4 additions & 4 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1895,7 +1895,7 @@ def _extract_resource(self, manager, zip_path): # noqa: C901
try:
rename(tmpnam, real_path)

except os.error:
except OSError:
if os.path.isfile(real_path):
if self._is_current(real_path, zip_path):
# the file became current since it was checked above,
Expand All @@ -1908,7 +1908,7 @@ def _extract_resource(self, manager, zip_path): # noqa: C901
return real_path
raise

except os.error:
except OSError:
# report a user-friendly error
manager.extraction_error()

Expand Down Expand Up @@ -2901,7 +2901,7 @@ def __getattr__(self, attr):

def __dir__(self):
return list(
set(super(Distribution, self).__dir__())
set(super().__dir__())
| set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))
)

Expand Down Expand Up @@ -3168,7 +3168,7 @@ class RequirementParseError(packaging.requirements.InvalidRequirement):
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
super(Requirement, self).__init__(requirement_string)
super().__init__(requirement_string)
self.unsafe_name = self.name
project_name = safe_name(self.name)
self.project_name, self.key = project_name, project_name.lower()
Expand Down
4 changes: 2 additions & 2 deletions pkg_resources/tests/test_working_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def parametrize_test_working_set_resolve(*test_list):
requirements,
expected1,
expected2,
) = [
) = (
strip_comments(s.lstrip())
for s in textwrap.dedent(test).lstrip().split('\n\n', 5)
]
)
installed_dists = list(parse_distributions(installed_dists))
installable_dists = list(parse_distributions(installable_dists))
requirements = list(pkg_resources.parse_requirements(requirements))
Expand Down
20 changes: 20 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,27 @@ ignore = [
"ISC001",
"ISC002",
]
extend-select = [
"UP", # pyupgrade
]
extend-ignore = [
"UP015", # redundant-open-modes, explicit is prefered
"UP030", # temporarily disabled
"UP031", # temporarily disabled
"UP032", # temporarily disabled
"UP036", # temporarily disabled
]
extend-exclude = [
"**/_vendor",
"setuptools/_distutils",
"setuptools/config/_validate_pyproject",
]

[format]
extend-exclude = [
"**/_vendor",
"setuptools/_distutils",
"setuptools/config/_validate_pyproject",
]
# https://docs.astral.sh/ruff/settings/#format-quote-style
quote-style = "preserve"
2 changes: 1 addition & 1 deletion setuptools/build_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ def run_setup(self, setup_script='setup.py'):
sys.argv[0] = setup_script

try:
super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
super().run_setup(setup_script=setup_script)
finally:
# While PEP 517 frontends should be calling each hook in a fresh
# subprocess according to the standard (and thus it should not be
Expand Down
9 changes: 3 additions & 6 deletions setuptools/command/bdist_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,7 @@ def walk_egg(egg_dir):
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
yield from walker


def analyze_egg(egg_dir, stubs):
Expand Down Expand Up @@ -406,14 +405,12 @@ def scan_module(egg_dir, base, name, stubs):

def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
yield from code.co_names
for const in code.co_consts:
if isinstance(const, str):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
yield from iter_symbols(const)


def can_scan():
Expand Down
8 changes: 3 additions & 5 deletions setuptools/command/easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -1743,8 +1743,7 @@ class RewritePthDistributions(PthDistributions):
@classmethod
def _wrap_lines(cls, lines):
yield cls.prelude
for line in lines:
yield line
yield from lines
yield cls.postlude

prelude = _one_liner(
Expand Down Expand Up @@ -2024,7 +2023,7 @@ def chmod(path, mode):
log.debug("changing mode of %s to %o", path, mode)
try:
_chmod(path, mode)
except os.error as e:
except OSError as e:
log.debug("chmod failed: %s", e)


Expand Down Expand Up @@ -2180,8 +2179,7 @@ def get_args(cls, dist, header=None):
cls._ensure_safe_name(name)
script_text = cls.template % locals()
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
yield res
yield from args

@staticmethod
def _ensure_safe_name(name):
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/editable_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
self.path_entries = path_entries

def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
entries = "\n".join((str(p.resolve()) for p in self.path_entries))
entries = "\n".join(str(p.resolve()) for p in self.path_entries)
contents = _encode_pth(f"{entries}\n")
wheel.writestr(f"__editable__.{self.name}.pth", contents)

Expand Down
5 changes: 2 additions & 3 deletions setuptools/command/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
def walk_revctrl(dirname=''):
"""Find all files under revision control"""
for ep in metadata.entry_points(group='setuptools.file_finders'):
for item in ep.load()(dirname):
yield item
yield from ep.load()(dirname)


class sdist(orig.sdist):
Expand Down Expand Up @@ -190,7 +189,7 @@ def _manifest_is_not_generated(self):

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

def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and use it to
Expand Down
6 changes: 2 additions & 4 deletions setuptools/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,11 +912,9 @@ def get_cmdline_options(self):
def iter_distribution_names(self):
"""Yield all packages, modules, and extension names in distribution"""

for pkg in self.packages or ():
yield pkg
yield from self.packages or ()

for module in self.py_modules or ():
yield module
yield from self.py_modules or ()

for ext in self.ext_modules or ():
if isinstance(ext, tuple):
Expand Down
5 changes: 2 additions & 3 deletions setuptools/glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ def glob0(dirname, basename):
def glob2(dirname, pattern):
assert _isrecursive(pattern)
yield pattern[:0]
for x in _rlistdir(dirname):
yield x
yield from _rlistdir(dirname)


# Recursively yields relative pathnames inside a literal directory.
Expand All @@ -126,7 +125,7 @@ def _rlistdir(dirname):
dirname = os.curdir
try:
names = os.listdir(dirname)
except os.error:
except OSError:
return
for x in names:
yield x
Expand Down
1 change: 0 additions & 1 deletion setuptools/msvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"""

import json
from io import open
from os import listdir, pathsep
from os.path import join, isfile, isdir, dirname
from subprocess import CalledProcessError
Expand Down
10 changes: 4 additions & 6 deletions setuptools/package_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,13 @@ def egg_info_for_url(url):
def distros_for_url(url, metadata=None):
"""Yield egg or source distribution objects that might be found at a URL"""
base, fragment = egg_info_for_url(url)
for dist in distros_for_location(url, base, metadata):
yield dist
yield from distros_for_location(url, base, metadata)
if fragment:
match = EGG_FRAGMENT.match(fragment)
if match:
for dist in interpret_distro_name(
yield from interpret_distro_name(
url, match.group(1), metadata, precedence=CHECKOUT_DIST
):
yield dist
)


def distros_for_location(location, basename, metadata=None):
Expand Down Expand Up @@ -516,7 +514,7 @@ def obtain(self, requirement, installer=None):
if dist in requirement:
return dist
self.debug("%s does not match %s", requirement, dist)
return super(PackageIndex, self).obtain(requirement, installer)
return super().obtain(requirement, installer)

def check_hash(self, checker, filename, tfp):
"""
Expand Down
3 changes: 1 addition & 2 deletions setuptools/tests/integration/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
def run(cmd, env=None):
r = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
universal_newlines=True,
env={**os.environ, **(env or {})},
# ^-- allow overwriting instead of discarding the current env
Expand Down
2 changes: 0 additions & 2 deletions setuptools/tests/test_archive_util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

import tarfile
import io

Expand Down
4 changes: 2 additions & 2 deletions setuptools/tests/test_build_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class BuildBackend(BuildBackendBase):
"""PEP 517 Build Backend"""

def __init__(self, *args, **kwargs):
super(BuildBackend, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.pool = futures.ProcessPoolExecutor(max_workers=1)

def __getattr__(self, name):
Expand Down Expand Up @@ -73,7 +73,7 @@ def _kill(self, pid):

class BuildBackendCaller(BuildBackendBase):
def __init__(self, *args, **kwargs):
super(BuildBackendCaller, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

(self.backend_name, _, self.backend_obj) = self.backend_name.partition(':')

Expand Down
4 changes: 2 additions & 2 deletions setuptools/tests/test_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def test_provides_extras_deterministic_order():
# Invalid value type.
(
{
'hello': str('*.msg'),
'hello': '*.msg',
},
(
"\"values of 'package_data' dict\" "
Expand All @@ -142,7 +142,7 @@ def test_check_package_data(package_data, expected_message):
assert check_package_data(None, 'package_data', package_data) is None
else:
with pytest.raises(DistutilsSetupError, match=re.escape(expected_message)):
check_package_data(None, str('package_data'), package_data)
check_package_data(None, 'package_data', package_data)


def test_check_specifier():
Expand Down
Loading

0 comments on commit d3048fc

Please sign in to comment.