Answer a question

I have a function which returns a function. I would like to find a proper type annotation. However, the returned function has *args and *kwargs. How is that annotated within Callable[[Parameters???], ReturnType]?

Example:

from typing import Callable
import io
import pandas as pd

def get_conversion_function(file_type: str) -> Callable[[io.BytesIO, TODO], pd.DataFrame]:
    def to_csv(bytes_, *args, **kwargs):
        return pd.read_csv(bytes_, **kwargs)
    if file_type == "csv":
        return to_csv

Answers

As I know, python's typing does not allow do that straightforwardly as stated in the docs of typing.Callable:

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType.

But you could use mypy extensions like this:

from typing import Callable
from mypy_extensions import Arg, VarArg, KwArg

def foo(a: str, *args: int, **kwargs: float) -> str:
    return 'Hello, {}'.format(a)
    
def bar() -> Callable[[Arg(str, 'a'), VarArg(int), KwArg(float)], str]:
    return foo

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐