Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a function complies with a signature specified by Callable[]

A function in Python may receive as an argument a choice of functions with different signatures. The signatures are specified using typing.Callable. Is there a way to check the received function against the specification and decide which one of them was actually given as parameter?

Example:

Option1 = Callable[[int], str]
Option2 = Callable[[str], str]

def somefunc(f: Union[Option1, Option2]):
   # I want to check here if f is of type Option1 or Option2
like image 967
avishorp Avatar asked Oct 27 '25 08:10

avishorp


1 Answers

Out of left field, here is a very different approach using Abstract Base Classes. The callables option1 and option2 here are legitimate instances of Option1 and Option2, respectively:

from abc import ABC, abstractmethod
from typing import Union


class Option1(ABC):
    @abstractmethod
    def __call__(self, _: int) -> str:
        ...


class Option2(ABC):
    @abstractmethod
    def __call__(self, _: str) -> str:
        ...


class Option1Impl(Option1):
    def __call__(self, _: int) -> str:
        return "takes int"


class Option2Impl(Option2):
    def __call__(self, _: str) -> str:
        return "takes str"


option1 = Option1Impl()
option2 = Option2Impl()


def somefunc(f: Union[Option1, Option2]) -> str:
    if isinstance(f, Option1):
        return "Option1"
    elif isinstance(f, Option2):
        return "Option2"
    else:
        raise TypeError(f"Got f of unexpected type: {type(f)}")


assert somefunc(option1) == "Option1"
assert somefunc(option2) == "Option2"
like image 146
Jasha Avatar answered Oct 28 '25 20:10

Jasha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!