Python function pointer type

For Python 3, it turned out to be good practice for me to hint at data types for function parameters and return types. For instance:

def icecream_factory(taste: str='Banana') -> Ice:
    ice = Ice(taste)
    ice.add_cream()
    return ice

This works great for all simple data types and classes. But now I need to use this with a "function pointer":

class NotificationRegister:

    def __init__(self):
        self.__function_list = list()
        """:type: list[?????]"""

    def register(self, function_pointer: ?????) -> None:
        self.__function_list.append(function_pointer)

def callback():
    pass

notification_register = NotificationRegister()
notification_register.register(callback)

What needs to be put in ?????to make it clear that a function pointer is needed here? I tried functionbecause type(callback)- <class 'function'>, but the keyword functionis undefined.

+4
source share
2 answers

I would use types.FunctionTypeto represent the function:

>>> import types
>>> types.FunctionType
<class 'function'>
>>>
>>> def func():
...     pass
...
>>> type(func)
<class 'function'>
>>> isinstance(func, types.FunctionType)
True
>>>

, 'function', , .

+6

collections.abc.Callable:

>>> import collections.abc
>>> def f(): pass
>>> isinstance(f, collections.abc.Callable)
True

, __call__. , True , __call__. , - , .

+1

Source: https://habr.com/ru/post/1569631/


All Articles