Home > OS >  Type hint callback function with optional parameters (aka Callable with optional parameter)
Type hint callback function with optional parameters (aka Callable with optional parameter)

Time:12-24

How do I specify the type of a callback function which takes an optional parameter?

For example, I have the following function:

def getParam(param: str = 'default'):
  return param

I'd like to pass it on as a callback function and use it both as Callable[[str], str] and Callable[[], str]:

def call(callback: Callable[[<???>], str]):
  return callback()   callback('a')

What do I write for <???>? I've tried Python's Optional but that does not work, as it still enforces a parameter (even if with value None) to be present.


For reference, I'm basically searching for the equivalent of the following TypeScript:

function call(callback: (a?: string) => string) {
  return callback()   callback('a');
}

CodePudding user response:

There is no syntax to indicate optional or keyword arguments https://docs.python.org/3/library/typing.html#typing.Callable

However you can use something like this

from typing import Protocol


class MyCallback(Protocol):
    def __call__(self, x: int =5): ...


def foo(callback: MyCallback):
    callback()  # <- IDE is fine with both of these lines
    callback(7)
  • Related