[Python-Dev] Can/should built-in functions get __get__?

Terry Reedy tjreedy at udel.edu
Fri Sep 5 01:54:51 CEST 2008


One of the nice features of 3.0 is that differences between classes 
defined in C and Python (other than speed) are mostly erased or hidden 
from the view of a Python programmer.

However, there are still sometimes surprising and quite visible 
differences between 'functions' written in C and Python.  Can these be 
better unified also?

In particular, built-in functions, in spite of of being labeled 
'builtin_function_or_method', are not usable as methods because they 
lack the __get__ method needed to bind function to instance.

[Q. Any reason to not shorten that to 'built-in function'?]

So, as a c.l.p poster discovered, within a class statement,

__hash__ = lambda x: id(x) # works, while the apparently cleaner
__hash__ = id # raises TypeError: id() takes exactly one argument (0 given)

[Irony: trivial lambda wrapping, lambda x: f(x) has been described here 
as useless and diseased, but is seems that casting 'built-in function' 
to 'function' is not so completely useless. ;-]

In this case, __hash__ = object.__hash__ is available, as is 
object.__repr__, but this is not true in general for C functions.

The difference between a C function and a C method wrapper is 
tantalizingly small:

 >>> i = set(dir(id))
 >>> h = set(dir(object.__hash__))
 >>> i-h
{'__module__', '__self__'}
 >>> h-i
{'__objclass__', '__get__'}

Similarly, for
 >>> def f(): pass

 >>> ff = set(dir(f))
 >>> ff - i
{'__defaults__', '__annotations__', '__kwdefaults__', '__globals__', 
'__closure__', '__dict__', '__code__', '__get__'}

the only un-obvious difference is __get__,

So I cannot help but wonder: is this is essential? or could it be 
removed but has not yet?  Could the object wrapper for C functions get a 
__get__ method so they become methods when accessed via a class just 
like Python functions do?

Terry Jan Reedy



More information about the Python-Dev mailing list