Skip to content

Commit

Permalink
Remove calls to typing.cast with better type narrowing
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam committed May 21, 2024
1 parent 5cbf12a commit 25a71b6
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 19 deletions.
1 change: 1 addition & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
python_version = 3.8
strict = False
warn_unused_ignores = True
warn_redundant_casts = True
# required to support namespace packages: https://github.com/python/mypy/issues/14057
explicit_package_bases = True
exclude = (?x)(
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 @@ -519,7 +519,7 @@ def template_vars(self) -> Tuple[str, str, Dict[str, str], Dict[str, List[str]]]
)

legacy_namespaces = {
cast(str, pkg): find_package_path(pkg, roots, self.dist.src_root or "")
pkg: find_package_path(pkg, roots, self.dist.src_root or "")
for pkg in self.dist.namespace_packages or []
}

Expand Down
16 changes: 11 additions & 5 deletions setuptools/config/_apply_pyprojecttoml.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import logging
import os
from collections.abc import Mapping
from email.headerregistry import Address
from functools import partial, reduce
from inspect import cleandoc
Expand All @@ -22,6 +21,7 @@
Callable,
Dict,
List,
Mapping,
Optional,
Set,
Tuple,
Expand All @@ -39,7 +39,7 @@
from setuptools.dist import Distribution # noqa

EMPTY: Mapping = MappingProxyType({}) # Immutable dict-like
_DictOrStr = Union[dict, str]
_LongDescriptionValue = Union[str, Mapping[str, str]]
_CorrespFn = Callable[["Distribution", Any, StrPath], None]
_Correspondence = Union[str, _CorrespFn]

Expand Down Expand Up @@ -153,15 +153,17 @@ def _guess_content_type(file: str) -> Optional[str]:
raise ValueError(f"Undefined content type for {file}, {msg}")


def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: StrPath):
def _long_description(
dist: "Distribution", val: _LongDescriptionValue, root_dir: StrPath
):
from setuptools.config import expand

if isinstance(val, str):
file: Union[str, list] = val
file: Union[str, tuple[()]] = val
text = expand.read_files(file, root_dir)
ctype = _guess_content_type(val)
else:
file = val.get("file") or []
file = val.get("file") or ()
text = val.get("text") or expand.read_files(file, root_dir)
ctype = val["content-type"]

Expand All @@ -171,6 +173,10 @@ def _long_description(dist: "Distribution", val: _DictOrStr, root_dir: StrPath):
_set_config(dist, "long_description_content_type", ctype)

if file:
# Due to bad type narrowing, mypy sees file as `str | tuple[Any, ...]`
# and flipping the condition mypy sees val as `str | None`.
# Pyright gets both w/o issue. Can't use `tuple[()]()` until Python 3.9. So casting instead.
# https://github.com/python/mypy/issues/17273
dist._referenced_files.add(cast(str, file))


Expand Down
20 changes: 7 additions & 13 deletions setuptools/config/expand.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
Tuple,
TypeVar,
Union,
cast,
)
from pathlib import Path
from types import ModuleType
Expand Down Expand Up @@ -119,7 +118,7 @@ def glob_relative(
return expanded_values


def read_files(filepaths: Union[str, bytes, Iterable[StrPath]], root_dir=None) -> str:
def read_files(filepaths: Union[StrPath, Iterable[StrPath]], root_dir=None) -> str:
"""Return the content of the files concatenated using ``\n`` as str
This function is sandboxed and won't reach anything outside ``root_dir``
Expand Down Expand Up @@ -339,18 +338,13 @@ def version(value: Union[Callable, Iterable[Union[str, int]], str]) -> str:
"""When getting the version directly from an attribute,
it should be normalised to string.
"""
if callable(value):
value = value()
_value = value() if callable(value) else value

value = cast(Iterable[Union[str, int]], value)

if not isinstance(value, str):
if hasattr(value, '__iter__'):
value = '.'.join(map(str, value))
else:
value = '%s' % value

return value
if isinstance(_value, str):
return _value
if hasattr(_value, '__iter__'):
return '.'.join(map(str, _value))
return '%s' % _value


def canonic_package_data(package_data: dict) -> dict:
Expand Down
1 change: 1 addition & 0 deletions setuptools/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ class Distribution(_Distribution):
}

_patched_dist = None
namespace_packages: List[str]

def patch_missing_pkg_info(self, attrs):
# Fake up a replacement for the data that would normally come from
Expand Down

0 comments on commit 25a71b6

Please sign in to comment.