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))
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).
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With