【问题标题】:How to typehint a callable with arbitrary argument list (vararg)如何使用任意参数列表 (vararg) 键入可调用对象
【发布时间】:2021-06-07 14:49:11
【问题描述】:

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

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 会出现以下异常: Incompatible return value type (got "Callable[[VarArg(Union[str, bytes, _PathLike[str], _PathLike[bytes]])], None]", expected "Callable[[List[Union[str, bytes, _PathLike[str], _PathLike[bytes]]]], None]")

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

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:

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

    【讨论】:

    • def delete_file_if_exists() -> Callable[[VarArg(AnyPath)], None] (with from mypy_extensions import VarArg) 确实是正确的解决方案
    猜你喜欢
    • 2015-12-31
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2010-10-07
    • 1970-01-01
    相关资源
    最近更新 更多