Skip to content

Commit

Permalink
Replace '_starfilter' with 'jaraco.functools.splat'.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Nov 5, 2023
1 parent 4d82dc4 commit 5deb5ac
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 8 deletions.
53 changes: 53 additions & 0 deletions distutils/_functools.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import collections.abc
import functools


Expand All @@ -18,3 +19,55 @@ def wrapper(param, *args, **kwargs):
return func(param, *args, **kwargs)

return wrapper


# from jaraco.functools 4.0
@functools.singledispatch
def _splat_inner(args, func):
"""Splat args to func."""
return func(*args)


@_splat_inner.register
def _(args: collections.abc.Mapping, func):
"""Splat kargs to func as kwargs."""
return func(**args)


def splat(func):
"""
Wrap func to expect its parameters to be passed positionally in a tuple.
Has a similar effect to that of ``itertools.starmap`` over
simple ``map``.
>>> import itertools, operator
>>> pairs = [(-1, 1), (0, 2)]
>>> _ = tuple(itertools.starmap(print, pairs))
-1 1
0 2
>>> _ = tuple(map(splat(print), pairs))
-1 1
0 2
The approach generalizes to other iterators that don't have a "star"
equivalent, such as a "starfilter".
>>> list(filter(splat(operator.add), pairs))
[(0, 2)]
Splat also accepts a mapping argument.
>>> def is_nice(msg, code):
... return "smile" in msg or code == 0
>>> msgs = [
... dict(msg='smile!', code=20),
... dict(msg='error :(', code=1),
... dict(msg='unknown', code=0),
... ]
>>> for msg in filter(splat(is_nice), msgs):
... print(msg)
{'msg': 'smile!', 'code': 20}
{'msg': 'unknown', 'code': 0}
"""
return functools.wraps(func)(functools.partial(_splat_inner, func=func))
10 changes: 2 additions & 8 deletions distutils/dep_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from .errors import DistutilsFileError
from .py39compat import zip_strict
from ._functools import splat


def _newer(source, target):
Expand All @@ -27,13 +28,6 @@ def newer(source, target):
return _newer(source, target)


def _starfilter(pred, iterables):
"""
Like itertools.starmap but for filter.
"""
return filter(lambda x: pred(*x), iterables)


def newer_pairwise(sources, targets):
"""
Filter filenames where sources are newer than targets.
Expand All @@ -43,7 +37,7 @@ def newer_pairwise(sources, targets):
targets) where source is newer than target, according to the semantics
of 'newer()'.
"""
newer_pairs = _starfilter(newer, zip_strict(sources, targets))
newer_pairs = filter(splat(newer), zip_strict(sources, targets))
return tuple(map(list, zip(*newer_pairs)))


Expand Down

0 comments on commit 5deb5ac

Please sign in to comment.