InspectFunction ABC for function-like objects


(Jeroen Demeyer) #1

Hello,

I would like to propose an ABC for “objects behaving like Python functions”, say collections.abc.InspectFunction. Python’s function type (for Python functions, not built-in functions) would have that ABC.

Required attributes are __name__ and __doc__. Also support for inspect.signature() and inspect.getfile() is required. Since an ABC is typically defined by attributes, I would go further and also require __signature__ and __file__ attributes. That means that those two attributes should be added to the function class (where they would be implemented as descriptors). Then inspect.signature could be changed to just return the __signature__ attribute and inspect.getfile should always check for a __file__ attribute.

Finally, inspect.isfunction() would be implemented by checking for that ABC instead of checking for the function type. That’s also the rationale for the name InspectFunction: it represents things that inspect considers functions and on which various inspect functions can be called.

The rationale of all this is that it should be possible to define custom classes behaving just like Python functions. Tools like Sphinx should document them exactly as they document Python functions. I am mainly thinking to apply this to function classes implementing PEP 580, but this would also apply to various things from functools such as functools.lru_cache or functools.partial.

I am planning to write a PEP for this, but I wanted to check here first.