csiz
csiz

Reputation: 5180

Is there a standard way to specify the type of a callback function in a docstring?

I have a function which accepts a callback. Is there a standard way to document the type of this parameter?

def example(callback):
    """Example function.

    Parameters
    ----------
    callback : type
       Description of `callback`.
    """
    print(callback(3, 14))

Upvotes: 21

Views: 18697

Answers (2)

Tom Wojcik
Tom Wojcik

Reputation: 6179

I needed something like that and while I think that callback should always be a function, AFAIK there's no way to specify the type of a function and I kept reusing callbacks with the same arguments doing different things so that's what I came up with.

import abc


class BaseCallback(metaclass=abc.ABCMeta):
    def __init__(self, param: int):
        self.param = param
        self.do_things()

    @abc.abstractmethod
    def do_things(self) -> int:
        raise NotImplementedError


class MyCallback(BaseCallback):
    def do_things(self):
        return self.param * 2


def func(callback: BaseCallback):  # type of callback specified
    callback()


func(callback=MyCallback)

You don't need to run the do_things method in init (imo it's ugly), depends on how much power do you have regarding where/when callback is run.

Upvotes: 1

csiz
csiz

Reputation: 5180

Found the answer while formulating the question, but the question itself doesn't give any results on Google.

PEP-0484 introduces type annotation in python. For example the type of a callback function taking two integers and returning a string is:

from typing import Callable

Callable[[int, int], str]

Upvotes: 29

Related Questions