python / python/mypy

Union of ParamSpec?

オープン
#17,481 コメント 1 件 リアクション 16 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Feature

Currently it's possible to concatenate a type to a paramspec to get a new paramspec.

I think I may need the ability to concatenate two paramspecs, like:

P = ParamSpec('P')
Q = ParamSpec('Q')
R = TypeVar("R")
Callable[Concatenate[P, Q], R]

Pitch

I'm trying to describe partial-like functions, I spotted https://github.com/python/mypy/pull/16939 which solves if for functools.partial (which is good) but still not giving a way to describe other partial-like functions.

Currently I can successfully describe the "removal" of one or multiple parameters:

from collections.abc import Callable
from typing import Concatenate, Generic, ParamSpec, TypeVar

P = ParamSpec('P')
Q = ParamSpec('Q')
S = TypeVar('S')
T = TypeVar('T')
U = TypeVar('U')


def substract_one_parameter(given: T, func: Callable[Concatenate[T, P], U]) -> Callable[P, U]:
    def inner(*args: P.args, **kwargs: P.kwargs) -> U:
        return func(given, *args, **kwargs)
    return inner


def substract_two_parameters(first: S, second: T, func: Callable[Concatenate[S, T, P], U]) -> Callable[P, U]:
    def inner(*args: P.args, **kwargs: P.kwargs) -> U:
        return func(first, second, *args, **kwargs)
    return inner


def int_int_int(a: int, b: int) -> int:
    return a + b


c = substract_one_parameter(1, int_int_int)
reveal_type(c)  # def (b: builtins.int) -> builtins.int
print(c(2))


d = substract_two_parameters(1, 2, int_int_int)
reveal_type(d)  # def () -> builtins.int
print(d())

But what I think I need is:

# P are the "removed" parameters
# Q are the "kept" parameters
def substract_n_parameters(func: Callable[Concatenate[P, Q], U], *outer_args: P.args, **outer_kwargs: P.kwargs) -> Callable[Q, U]:
    def inner(*args: Q.args, **kwargs: Q.kwargs) -> U:
        return func(*outer_args, *args, **outer_kwargs, **kwargs)
    return inner

I feel that would cleanly express the "removal" of P from [P, Q], without the need to introduce a new function like Difference[P, Q].

I feel like this could also be used for the real functools.partial, maybe simplifying the current (working, yeah) implementation.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

ソースファイルやテストは指定されていません。まず、既存の ParamSpec と Concatenate の動作を提示された例と比較し、次に参照されている functools.partial の実装と pull request を確認してください。2 つの ParamSpec を連結できるかどうかを判断し、提案された substract_n_parameters の型付け動作を検証できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
developer-experience, devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。