Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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))
like image 402
csiz Avatar asked Oct 28 '15 18:10

csiz


People also ask

What are the types of callback?

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).

When callback function is called?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


2 Answers

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]
like image 180
csiz Avatar answered Oct 27 '22 08:10

csiz


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.

like image 45
Tom Wojcik Avatar answered Oct 27 '22 08:10

Tom Wojcik