简体   繁体   中英

How to typehint a callable with arbitrary argument list (vararg)

I am trying to typehint a function that looks like this:

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

And I wonder how to exactly type it:

1.

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

works but does not specify the type of variable arguments

2.

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

does not work but a mypy run on it gives the following exception: 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]")

So I am wondering if I could do something with this VarArg (that I can not manage to import) or if I am stuck with an elipsis typing.

You can import the type VarArg with mypy-extension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM