Skip to content

Commit

Permalink
(Mostly) automatic updates from Ruff for Python 3.9+
Browse files Browse the repository at this point in the history
  • Loading branch information
abravalheri committed Oct 31, 2024
1 parent c032a5b commit d2e7e70
Show file tree
Hide file tree
Showing 33 changed files with 93 additions and 112 deletions.
17 changes: 6 additions & 11 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,17 @@
import warnings
import zipfile
import zipimport
from collections.abc import Iterable, Iterator, Mapping, MutableSequence
from pkgutil import get_importer
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Iterator,
Literal,
Mapping,
MutableSequence,
NamedTuple,
NoReturn,
Protocol,
Tuple,
TypeVar,
Union,
overload,
Expand Down Expand Up @@ -424,7 +419,7 @@ def get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribu
return _find_adapter(_provider_factories, loader)(module)


@functools.lru_cache(maxsize=None)
@functools.cache
def _macos_vers():
version = platform.mac_ver()[0]
# fallback for MacPorts
Expand Down Expand Up @@ -1120,7 +1115,7 @@ def __setstate__(self, e_k_b_n_c) -> None:
self.callbacks = callbacks[:]


class _ReqExtras(Dict["Requirement", Tuple[str, ...]]):
class _ReqExtras(dict["Requirement", tuple[str, ...]]):
"""
Map each requirement to the extras that demanded it.
"""
Expand Down Expand Up @@ -1952,7 +1947,7 @@ def __init__(self) -> None:
empty_provider = EmptyProvider()


class ZipManifests(Dict[str, "MemoizedZipManifests.manifest_mod"]):
class ZipManifests(dict[str, "MemoizedZipManifests.manifest_mod"]):
"""
zip manifest builder
"""
Expand Down Expand Up @@ -2069,7 +2064,7 @@ def _extract_resource(self, manager: ResourceManager, zip_path) -> str: # noqa:
# return the extracted directory name
return os.path.dirname(last)

timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
timestamp, _size = self._get_date_and_size(self.zipinfo[zip_path])

if not WRITE_SUPPORT:
raise OSError(
Expand Down Expand Up @@ -2662,7 +2657,7 @@ def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ...

else:

@functools.lru_cache(maxsize=None)
@functools.cache
def _normalize_cached(filename):
return normalize_path(filename)

Expand Down
6 changes: 3 additions & 3 deletions pkg_resources/tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,11 +693,11 @@ def test_requirements_with_markers(self):
) != Requirement.parse("name[foo,bar]==1.0;python_version=='3.6'")

def test_local_version(self):
(req,) = parse_requirements('foo==1.0+org1')
parse_requirements('foo==1.0+org1')

def test_spaces_between_multiple_versions(self):
(req,) = parse_requirements('foo>=1.0, <3')
(req,) = parse_requirements('foo >= 1.0, < 3')
parse_requirements('foo>=1.0, <3')
parse_requirements('foo >= 1.0, < 3')

@pytest.mark.parametrize(
['lower', 'upper'],
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def pypi_link(pkg_filename):
dependency link for PyPI.
"""
root = 'https://files.pythonhosted.org/packages/source'
name, sep, rest = pkg_filename.partition('-')
name, _sep, _rest = pkg_filename.partition('-')
parts = root, name[0], name, pkg_filename
return '/'.join(parts)

Expand Down
2 changes: 1 addition & 1 deletion setuptools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, attrs: Mapping[str, object]):
def _get_project_config_files(self, filenames=None):
"""Ignore ``pyproject.toml``, they are not related to setup_requires"""
try:
cfg, toml = super()._split_standard_project_metadata(filenames)
cfg, _toml = super()._split_standard_project_metadata(filenames)
except Exception:
return filenames, ()
return cfg, ()
Expand Down
3 changes: 2 additions & 1 deletion setuptools/_reqs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

from collections.abc import Iterable, Iterator
from functools import lru_cache
from typing import TYPE_CHECKING, Callable, Iterable, Iterator, TypeVar, Union, overload
from typing import TYPE_CHECKING, Callable, TypeVar, Union, overload

import jaraco.text as text
from packaging.requirements import Requirement
Expand Down
5 changes: 3 additions & 2 deletions setuptools/build_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@
import tempfile
import tokenize
import warnings
from collections.abc import Iterable, Iterator, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, Iterator, List, Mapping, Union
from typing import TYPE_CHECKING, Union

import setuptools

Expand Down Expand Up @@ -146,7 +147,7 @@ def suppress_known_deprecation():
yield


_ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, List[str], None]], None]
_ConfigSettings: TypeAlias = Union[Mapping[str, Union[str, list[str], None]], None]
"""
Currently the user can run::
Expand Down
5 changes: 3 additions & 2 deletions setuptools/command/_requirestxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@

import io
from collections import defaultdict
from collections.abc import Mapping
from itertools import filterfalse
from typing import Dict, Mapping, TypeVar
from typing import TypeVar

from jaraco.text import yield_lines
from packaging.requirements import Requirement
Expand All @@ -22,7 +23,7 @@

# dict can work as an ordered set
_T = TypeVar("_T")
_Ordered = Dict[_T, None]
_Ordered = dict[_T, None]


def _prepare(
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/bdist_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def run(self): # noqa: C901 # is too complex (14) # FIXME
self.stubs = []
to_compile = []
for p, ext_name in enumerate(ext_outputs):
filename, ext = os.path.splitext(ext_name)
filename, _ext = os.path.splitext(ext_name)
pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py')
self.stubs.append(pyfile)
log.info("creating stub loader for %s", ext_name)
Expand Down
3 changes: 2 additions & 1 deletion setuptools/command/bdist_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
import sys
import sysconfig
import warnings
from collections.abc import Iterable, Sequence
from email.generator import BytesGenerator, Generator
from email.policy import EmailPolicy
from glob import iglob
from shutil import rmtree
from typing import TYPE_CHECKING, Callable, Iterable, Literal, Sequence, cast
from typing import TYPE_CHECKING, Callable, Literal, cast
from zipfile import ZIP_DEFLATED, ZIP_STORED

from packaging import tags, version as _packaging_version
Expand Down
5 changes: 3 additions & 2 deletions setuptools/command/build_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import itertools
import os
import sys
from collections.abc import Iterator
from importlib.machinery import EXTENSION_SUFFIXES
from importlib.util import cache_from_source as _compiled_file_name
from pathlib import Path
from typing import TYPE_CHECKING, Iterator
from typing import TYPE_CHECKING

from setuptools.dist import Distribution
from setuptools.errors import BaseError
Expand Down Expand Up @@ -459,7 +460,7 @@ def link_shared_object(

assert output_dir is None # distutils build_ext doesn't pass this
output_dir, filename = os.path.split(output_libname)
basename, ext = os.path.splitext(filename)
basename, _ext = os.path.splitext(filename)
if self.library_filename("x").startswith('lib'):
# strip 'lib' prefix; this is kludgy if some platform uses
# a different prefix
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/build_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import os
import stat
import textwrap
from collections.abc import Iterable, Iterator
from functools import partial
from glob import glob
from pathlib import Path
from typing import Iterable, Iterator

from more_itertools import unique_everseen

Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -1545,7 +1545,7 @@ def extract_wininst_cfg(dist_filename):
return None
f.seek(prepended - 12)

tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
tag, cfglen, _bmlen = struct.unpack("<iii", f.read(12))
if tag not in (0x1234567A, 0x1234567B):
return None # not a valid tag

Expand Down
3 changes: 2 additions & 1 deletion setuptools/command/editable_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@
import os
import shutil
import traceback
from collections.abc import Iterable, Iterator, Mapping
from contextlib import suppress
from enum import Enum
from inspect import cleandoc
from itertools import chain, starmap
from pathlib import Path
from tempfile import TemporaryDirectory
from types import TracebackType
from typing import TYPE_CHECKING, Iterable, Iterator, Mapping, Protocol, TypeVar, cast
from typing import TYPE_CHECKING, Protocol, TypeVar, cast

from .. import Command, _normalization, _path, errors, namespaces
from .._path import StrPath
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/install_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _all_packages(pkg_name):
"""
while pkg_name:
yield pkg_name
pkg_name, sep, child = pkg_name.rpartition('.')
pkg_name, _sep, _child = pkg_name.rpartition('.')

def _get_SVEM_NSPs(self):
"""
Expand Down
5 changes: 3 additions & 2 deletions setuptools/config/_apply_pyprojecttoml.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@

import logging
import os
from collections.abc import Mapping
from email.headerregistry import Address
from functools import partial, reduce
from inspect import cleandoc
from itertools import chain
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, TypeVar, Union
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union

from .._path import StrPath
from ..errors import RemovedConfigError
Expand All @@ -34,7 +35,7 @@


EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
_ProjectReadmeValue: TypeAlias = Union[str, Dict[str, str]]
_ProjectReadmeValue: TypeAlias = Union[str, dict[str, str]]
_Correspondence: TypeAlias = Callable[["Distribution", Any, Union[StrPath, None]], None]
_T = TypeVar("_T")

Expand Down
3 changes: 2 additions & 1 deletion setuptools/config/expand.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@
import os
import pathlib
import sys
from collections.abc import Iterable, Iterator, Mapping
from configparser import ConfigParser
from glob import iglob
from importlib.machinery import ModuleSpec, all_suffixes
from itertools import chain
from pathlib import Path
from types import ModuleType, TracebackType
from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, Mapping, TypeVar
from typing import TYPE_CHECKING, Any, Callable, TypeVar

from .._path import StrPath, same_path as _same_path
from ..discovery import find_package_path
Expand Down
3 changes: 2 additions & 1 deletion setuptools/config/pyprojecttoml.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@

import logging
import os
from collections.abc import Mapping
from contextlib import contextmanager
from functools import partial
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Mapping
from typing import TYPE_CHECKING, Any, Callable

from .._path import StrPath
from ..errors import FileError, InvalidConfigError
Expand Down
24 changes: 6 additions & 18 deletions setuptools/config/setupcfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,9 @@
import functools
import os
from collections import defaultdict
from collections.abc import Iterable, Iterator
from functools import partial, wraps
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generic,
Iterable,
Iterator,
List,
Tuple,
TypeVar,
cast,
)
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, TypeVar, cast

from packaging.markers import default_environment as marker_env
from packaging.requirements import InvalidRequirement, Requirement
Expand All @@ -48,13 +36,13 @@

from distutils.dist import DistributionMetadata

SingleCommandOptions: TypeAlias = Dict[str, Tuple[str, Any]]
SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]]
"""Dict that associate the name of the options of a particular command to a
tuple. The first element of the tuple indicates the origin of the option value
(e.g. the name of the configuration file where it was read from),
while the second element of the tuple is the option value itself
"""
AllCommandOptions: TypeAlias = Dict[str, SingleCommandOptions]
AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions]
"""cmd name => its options"""
Target = TypeVar("Target", "Distribution", "DistributionMetadata")

Expand Down Expand Up @@ -114,7 +102,7 @@ def _apply(

try:
# TODO: Temporary cast until mypy 1.12 is released with upstream fixes from typeshed
_Distribution.parse_config_files(dist, filenames=cast(List[str], filenames))
_Distribution.parse_config_files(dist, filenames=cast(list[str], filenames))
handlers = parse_configuration(
dist, dist.command_options, ignore_option_errors=ignore_option_errors
)
Expand Down Expand Up @@ -275,7 +263,7 @@ def _section_options(
cls, options: AllCommandOptions
) -> Iterator[tuple[str, SingleCommandOptions]]:
for full_name, value in options.items():
pre, sep, name = full_name.partition(cls.section_prefix)
pre, _sep, name = full_name.partition(cls.section_prefix)
if pre:
continue
yield name.lstrip('.'), value
Expand Down
4 changes: 2 additions & 2 deletions setuptools/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_version(self, paths=None, default: str = "unknown"):

if self.attribute is None:
try:
f, p, i = find_module(self.module, paths)
f, _p, _i = find_module(self.module, paths)
except ImportError:
return None
if f:
Expand Down Expand Up @@ -114,7 +114,7 @@ def get_module_constant(module, symbol, default: str | int = -1, paths=None):
constant. Otherwise, return 'default'."""

try:
f, path, (suffix, mode, kind) = info = find_module(module, paths)
f, path, (_suffix, _mode, kind) = info = find_module(module, paths)
except ImportError:
# Module doesn't exist
return None
Expand Down
4 changes: 2 additions & 2 deletions setuptools/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@

import itertools
import os
from collections.abc import Iterator
from collections.abc import Iterable, Iterator, Mapping
from fnmatch import fnmatchcase
from glob import glob
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, Iterable, Mapping
from typing import TYPE_CHECKING, ClassVar

import _distutils_hack.override # noqa: F401

Expand Down
Loading

0 comments on commit d2e7e70

Please sign in to comment.