[Python-Dev] PEP 575: Unifying function/method classes

Mark Shannon mark at hotpy.org
Mon Apr 30 09:38:58 EDT 2018


On 12/04/18 17:12, Jeroen Demeyer wrote:
> Dear Python developers,
> 
> I would like to request a review of PEP 575, which is about changing the 
> classes used for built-in functions and Python functions and methods. 
> The text of the PEP can be found at


The motivation of PEP 575 is to allow introspection of built-in 
functions and to allow functions implemented in Python to be 
re-implemented in C.

These are excellent goals.

The PEP then elaborates a complex class hierarchy, and various 
extensions to the C API.
This adds a considerable maintainance burden and restricts future
changes and optimisations to CPython.

While a unified *interface* makes sense, a unified class hierarchy and 
implementation, IMO, do not.

The hierarchy also seems to force classes that are dissimilar to share a 
common base-class.
Bound-methods may be callables, but they are not functions, they are a 
pair of a function and a "self" object.

As the PEP points out, Cython functions are able to mimic Python 
functions, why not do the same for CPython builtin-functions?

As an aside, rather than unifying the classes of all non-class 
callables, CPython's builtin-function class could be split in two. 
Currently it is both a bound-method and a function.
The name 'builtin_function_or_method' is a give away :)

Consider the most common "function" and "method" classes:

 >>> class C:
...    def f(self): pass

# "functions"

 >>> type(C.f)
<class 'function'>
 >>> type(len)
<class 'builtin_function_or_method'>
 >>> type(list.append)
<class 'method_descriptor'>
 >>> type(int.__add__)
<class 'wrapper_descriptor'>

# "bound-methods"

 >>> type(C().f)
<class 'method'>
 >>> type([].append)
<class 'builtin_function_or_method'>
 >>> type(1 .__add__)
<class 'method-wrapper'>

IMO, there are so many versions of "function" and "bound-method", that a 
unified class hierarchy and the resulting restriction to the 
implementation will make implementing a unified interface harder, not 
easier.

For "functions", all that is needed is to specify an interface, say a 
single property "__signature__".
Then all that a class that wants to be a "function" need do is have a 
"__signature__" property and be callable.

For "bound-methods", we should reuse the interface of 'method';
two properties, "__func__" and "__self__".


Cheers,
Mark.



More information about the Python-Dev mailing list