How to subclass the builtin function class in Python?

Viewed 167

In python you can add metadata to functions by way of attributes, as discussed in the Python data model:

Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions.

I have a function that takes another function as input, expecting it to have such a metadata attribute available. When using the type Callable to annotate this function, I cannot enforce this attribute being present. Hence, I want to rather make a subclass of the built in function class that ensures the presence of metadata, that I can use in type annotations.

There is only one small issue: I can't find references to this class except in runtime. For instance the builtins module does not have a function class as far as I can see.

1 Answers

It is not possible to subclass the built-in function type in Python.

>>> class MyFunction(type(lambda: None)):
...     pass
...
TypeError: Error when calling the metaclass bases
    type 'function' is not an acceptable base type

Consider using a callable class instead: create a user-defined type which documents the expected metadata attribute(s) and defines a __call__ method.

Related