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

Clean up and improve typing #378

Merged
merged 1 commit into from
Feb 9, 2021
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
5 changes: 1 addition & 4 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
ignore_missing_imports = True

# The following are the flags enabled by --strict
#
# Note: warn_unused_ignores is False due to incorrect typeshed annotations for
# platform.mac_ver()
warn_unused_configs = True
disallow_subclassing_any = True
disallow_any_generics = True
Expand All @@ -15,6 +12,6 @@ check_untyped_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_ignores = False
warn_unused_ignores = True
warn_return_any = True
no_implicit_reexport = True
54 changes: 18 additions & 36 deletions packaging/_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,81 +4,63 @@


class InfinityType:
def __repr__(self):
# type: () -> str
def __repr__(self) -> str:
return "Infinity"

def __hash__(self):
# type: () -> int
def __hash__(self) -> int:
return hash(repr(self))

def __lt__(self, other):
# type: (object) -> bool
def __lt__(self, other: object) -> bool:
return False

def __le__(self, other):
# type: (object) -> bool
def __le__(self, other: object) -> bool:
return False

def __eq__(self, other):
# type: (object) -> bool
def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__)

def __ne__(self, other):
# type: (object) -> bool
def __ne__(self, other: object) -> bool:
return not isinstance(other, self.__class__)

def __gt__(self, other):
# type: (object) -> bool
def __gt__(self, other: object) -> bool:
return True

def __ge__(self, other):
# type: (object) -> bool
def __ge__(self, other: object) -> bool:
return True

def __neg__(self):
# type: (object) -> NegativeInfinityType
def __neg__(self: object) -> "NegativeInfinityType":
return NegativeInfinity


Infinity = InfinityType()


class NegativeInfinityType:
def __repr__(self):
# type: () -> str
def __repr__(self) -> str:
return "-Infinity"

def __hash__(self):
# type: () -> int
def __hash__(self) -> int:
return hash(repr(self))

def __lt__(self, other):
# type: (object) -> bool
def __lt__(self, other: object) -> bool:
return True

def __le__(self, other):
# type: (object) -> bool
def __le__(self, other: object) -> bool:
return True

def __eq__(self, other):
# type: (object) -> bool
def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__)

def __ne__(self, other):
# type: (object) -> bool
def __ne__(self, other: object) -> bool:
return not isinstance(other, self.__class__)

def __gt__(self, other):
# type: (object) -> bool
def __gt__(self, other: object) -> bool:
return False

def __ge__(self, other):
# type: (object) -> bool
def __ge__(self, other: object) -> bool:
return False

def __neg__(self):
# type: (object) -> InfinityType
def __neg__(self: object) -> InfinityType:
return Infinity


Expand Down
48 changes: 0 additions & 48 deletions packaging/_typing.py

This file was deleted.

76 changes: 28 additions & 48 deletions packaging/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
import platform
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

from pyparsing import ( # noqa: N817
Forward,
Expand All @@ -19,15 +20,8 @@
stringStart,
)

from ._typing import TYPE_CHECKING
from .specifiers import InvalidSpecifier, Specifier

if TYPE_CHECKING: # pragma: no cover
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

Operator = Callable[[str, str], bool]


__all__ = [
"InvalidMarker",
"UndefinedComparison",
Expand All @@ -36,6 +30,8 @@
"default_environment",
]

Operator = Callable[[str, str], bool]


class InvalidMarker(ValueError):
"""
Expand All @@ -57,38 +53,31 @@ class UndefinedEnvironmentName(ValueError):


class Node:
def __init__(self, value):
# type: (Any) -> None
def __init__(self, value: Any) -> None:
self.value = value

def __str__(self):
# type: () -> str
def __str__(self) -> str:
return str(self.value)

def __repr__(self):
# type: () -> str
def __repr__(self) -> str:
return f"<{self.__class__.__name__}('{self}')>"

def serialize(self):
# type: () -> str
def serialize(self) -> str:
raise NotImplementedError


class Variable(Node):
def serialize(self):
# type: () -> str
def serialize(self) -> str:
return str(self)


class Value(Node):
def serialize(self):
# type: () -> str
def serialize(self) -> str:
return f'"{self}"'


class Op(Node):
def serialize(self):
# type: () -> str
def serialize(self) -> str:
return str(self)


Expand Down Expand Up @@ -149,16 +138,16 @@ def serialize(self):
MARKER = stringStart + MARKER_EXPR + stringEnd


def _coerce_parse_result(results):
# type: (Union[ParseResults, List[Any]]) -> List[Any]
def _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]:
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results


def _format_marker(marker, first=True):
# type: (Union[List[str], Tuple[Node, ...], str], Optional[bool]) -> str
def _format_marker(
marker: Union[List[str], Tuple[Node, ...], str], first: Optional[bool] = True
) -> str:

assert isinstance(marker, (list, tuple, str))

Expand All @@ -185,7 +174,7 @@ def _format_marker(marker, first=True):
return marker


_operators = {
_operators: Dict[str, Operator] = {
"in": lambda lhs, rhs: lhs in rhs,
"not in": lambda lhs, rhs: lhs not in rhs,
"<": operator.lt,
Expand All @@ -194,19 +183,18 @@ def _format_marker(marker, first=True):
"!=": operator.ne,
">=": operator.ge,
">": operator.gt,
} # type: Dict[str, Operator]
}


def _eval_op(lhs, op, rhs):
# type: (str, Op, str) -> bool
def _eval_op(lhs: str, op: Op, rhs: str) -> bool:
try:
spec = Specifier("".join([op.serialize(), rhs]))
except InvalidSpecifier:
pass
else:
return spec.contains(lhs)

oper = _operators.get(op.serialize()) # type: Optional[Operator]
oper: Optional[Operator] = _operators.get(op.serialize())
if oper is None:
raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")

Expand All @@ -220,9 +208,8 @@ class Undefined:
_undefined = Undefined()


def _get_env(environment, name):
# type: (Dict[str, str], str) -> str
value = environment.get(name, _undefined) # type: Union[str, Undefined]
def _get_env(environment: Dict[str, str], name: str) -> str:
value: Union[str, Undefined] = environment.get(name, _undefined)

if isinstance(value, Undefined):
raise UndefinedEnvironmentName(
Expand All @@ -232,9 +219,8 @@ def _get_env(environment, name):
return value


def _evaluate_markers(markers, environment):
# type: (List[Any], Dict[str, str]) -> bool
groups = [[]] # type: List[List[bool]]
def _evaluate_markers(markers: List[Any], environment: Dict[str, str]) -> bool:
groups: List[List[bool]] = [[]]

for marker in markers:
assert isinstance(marker, (list, tuple, str))
Expand All @@ -260,17 +246,15 @@ def _evaluate_markers(markers, environment):
return any(all(item) for item in groups)


def format_full_version(info):
# type: (sys._version_info) -> str
def format_full_version(info: "sys._version_info") -> str:
version = "{0.major}.{0.minor}.{0.micro}".format(info)
kind = info.releaselevel
if kind != "final":
version += kind[0] + str(info.serial)
return version


def default_environment():
# type: () -> Dict[str, str]
def default_environment() -> Dict[str, str]:
iver = format_full_version(sys.implementation.version)
implementation_name = sys.implementation.name
return {
Expand All @@ -289,8 +273,7 @@ def default_environment():


class Marker:
def __init__(self, marker):
# type: (str) -> None
def __init__(self, marker: str) -> None:
try:
self._markers = _coerce_parse_result(MARKER.parseString(marker))
except ParseException as e:
Expand All @@ -299,16 +282,13 @@ def __init__(self, marker):
f"{marker[e.loc : e.loc + 8]!r}"
)

def __str__(self):
# type: () -> str
def __str__(self) -> str:
return _format_marker(self._markers)

def __repr__(self):
# type: () -> str
def __repr__(self) -> str:
return f"<Marker('{self}')>"

def evaluate(self, environment=None):
# type: (Optional[Dict[str, str]]) -> bool
def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:
"""Evaluate a marker.

Return the boolean from evaluating the given marker against the
Expand Down
Loading