Python类型提示可使用一个已知的位置类型调用,然后使用*args和**kwargs

Python类型提示可使用一个已知的位置类型调用,然后使用*args和**kwargs,python,type-hinting,typing,mypy,Python,Type Hinting,Typing,Mypy,I以下函数foo,它具有: 一个具有已知类型的位置参数 之后位置参数和关键字参数的数量可变 输入import Callable def foo(条形图:str、*ARG、**kwargs)->无: “”“某些函数具有一个位置参数,然后是*args和**kwargs。”“” foo#:可调用[[str,…],None]=foo#错误:意外“…” 我如何输入提示 目前,mypy==0.812抛出错误:错误:意外的“…”[misc]您现在不能像Samwise的评论所说的那样执行此操作,但在Pyt

I以下函数
foo
,它具有:

  • 一个具有已知类型的位置参数
  • 之后位置参数和关键字参数的数量可变
输入import Callable
def foo(条形图:str、*ARG、**kwargs)->无:
“”“某些函数具有一个位置参数,然后是*args和**kwargs。”“”
foo#:可调用[[str,…],None]=foo#错误:意外“…”
我如何输入提示


目前,
mypy==0.812
抛出错误:
错误:意外的“…”[misc]
您现在不能像Samwise的评论所说的那样执行此操作,但在Python 3.10(下)中,您将能够执行此操作:

from typing import Callable, ParamSpec, Concatenate

P = ParamSpec("P")

def receive_foo(foo: Callable[Concatenate[str, P], None]):
    pass

我不确定您是否能够为它声明一个类型(因为
p
不能在全局范围内使用),因此您可能每次都必须指定
p
内联的类型。

您现在不能像Samwise的评论所说的那样执行此操作,但在Python 3.10(下)中,您将能够执行此操作:

from typing import Callable, ParamSpec, Concatenate

P = ParamSpec("P")

def receive_foo(foo: Callable[Concatenate[str, P], None]):
    pass

我不确定您是否能够为它声明一个(因为
p
不能在全局范围内使用),因此您可能每次都必须指定与
p
内联的类型。

我可能会为此使用协议。它们通常比callable更灵活。它看起来像这样

from typing import Protocol

class BarFunc(Protocol):
    def __call__(fakeself, bar: str, *args, **kwargs) -> None:
        # fakeself gets swallowed by the class method binding logic
        # so this will match functions that have bar and the free arguments.
        ...

def foo(bar: str, *args, **kwargs) -> None:
    """Some function with one positional arg and then *args and **kwargs."""

foo_: BarFunc = foo

我可能会为此使用协议。它们通常比callable更灵活。它看起来像这样

from typing import Protocol

class BarFunc(Protocol):
    def __call__(fakeself, bar: str, *args, **kwargs) -> None:
        # fakeself gets swallowed by the class method binding logic
        # so this will match functions that have bar and the free arguments.
        ...

def foo(bar: str, *args, **kwargs) -> None:
    """Some function with one positional arg and then *args and **kwargs."""

foo_: BarFunc = foo

据我所知,没有办法做到这一点——您只需将其键入
Callable[…,None]
。我通常尽量避免使用
*args
*kwargs
,因为在类型良好的界面中很难使用它们。据我所知,没有办法做到这一点——您只需将其键入为
可调用[…,无]
。我通常尽量避免使用
*args
*kwargs
,因为在类型良好的界面中很难使用它们。