python - 如何输入带有任意参数列表(vararg)的可调用函数

标签 python type-hinting python-typing

我正在尝试输入一个如下所示的函数:

def delete_file_if_exists():
    """Fixture providing a function that deletes a list of files of given filename it it exists
    """
    def deletion_function(*args: AnyPath) -> None:
        """A function deleting the file of given path if it exists
        :param args:The list of path to delete if file exists
        """
        for arg in args:
            if os.path.isfile(arg):
                os.remove(arg)
    return deletion_function

我想知道如何准确输入它:

1.

def delete_file_if_exists() -> Callable[..., None]:

可以工作,但不指定变量参数的类型

2.

def delete_file_if_exists() -> Callable[[List[AnyPath]], None]:

不起作用,但 mypy在其上运行会出现以下异常: 不兼容的返回值类型(得到“Callable[[VarArg(Union[str, bytes, _PathLike[str], _PathLike[bytes]])], None]”,预期为“Callable[[List[Union[str, bytes]” , _PathLike[str], _PathLike[字节]]]], 无]")

所以我想知道我是否可以用这个 VarArg 做一些事情(我无法导入)或者我是否陷入了省略号输入的困境。

最佳答案

您可以使用 mypy-extension 导入 VarArg 类型.

关于python - 如何输入带有任意参数列表(vararg)的可调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67873865/

相关文章:

python - 具有来自另一个模型的两个字段的django模型

python - 索引错误 : list index out of range in python while something not found

python - 如何键入提示具有封闭类类型的方法?

python - Numpy:如何向量化应用于数据集的函数的函数形式的参数

python - 不推荐使用 contextlib.nested 的第二种情况的说明(Python 文档)

python - 实例变量 Python 的类型提示约定

Clojure 给出反射警告而不是类型提示

python - 相同类型的多个参数的类型提示?

python - Python中是否有 "Addable"协议(protocol)或抽象基类?如果不是,又该如何定义呢?

python - 在 FastAPI 中使用 Annotated 会忽略 Query 中设置的规则