Home > Back-end >  How to write a Python type hint that specifies a Callable that takes certain parameters or 0 paramet
How to write a Python type hint that specifies a Callable that takes certain parameters or 0 paramet

Time:05-21

I have the following code

def func1(f: Callable):
    def decorator(*args, **kwargs):
        # do something
        return f(*args, **kwargs)

    return decorator


@func1
def func2(parameter: str):
    # do something else
    ...

I want to specify that func1 takes a Callable that has either 1 parameter of a certain type (in this case, a str), or no parameters at all so that I could use it not just with func2, but also with another function that takes no parameters like the following function

@func1
def func3():
    # this function doesn't take any parameters

Obviously even if there is a solution, it wouldn't actually be effective because type hints are ignored anyway, but I would like to add actual validation using Pydnatic, that's why I want to specify that the function must have a parameter of a certain type or no parameters at all.

CodePudding user response:

I want to specify that func1 takes a Callable that has either 1 parameter of a certain type (in this case, a str), or no parameters at all

Use the union of the two signatures:

 func : Callable[[str], Any] | Callable[[], Any])
  • Related