Search code examples
pythonpython-typing

Type a callable which accepts at least one argument


I was wondering how to type hint a callble that accepts at least one argument.

For example the following callables are acceptable:

def foo(x: int): ...
def bar(x: int, y: float): ...

class Baz:
  def __call__(self, x: int): ...

However, the following function isn't:

def noargs(): ...

I have tried using *args and **kwargs but this enforces the accepted callables to receive them along with the other (actual) arguments.


Solution

  • You can use typing.Concatenate to build a variadic signature.

    from collections.abc import Callable, Any
    from typing import Concatenate
    
    def foo(f: Callable[Concatenate[int, ...], None]):
        pass
    

    foo accepts a callable that accepts at the very least a (first) argument of type int, with 0 or more additional positional arguments accepted (and returns None).