[FIXED] How to write a Python type hint that specifies a Callable that takes certain parameters or 0 parameters?

Issue

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.


Solution

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])


Answered By - Raymond Hettinger
Answer Checked By - Cary Denson (Python.Easybugfix Admin)

Related Posts

Post a Comment